springboot整合redssion

导入依赖包



 <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson-spring-data-20</artifactId>
            <version>3.9.1</version>
        </dependency>
        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson</artifactId>
            <version>3.9.1</version>
        </dependency>

配置文件

package com.common.redission;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Slf4j
@Configuration
public class RedissionConfig {

    @Resource
    private RedisProperties redisProperties;

    @Bean
    public RedissonClient redissonClient(){
        RedissonClient redissonClient;
        Config config = new Config();
        Integer port = redisProperties.getPort();
        if (port == 0) {
            port = 6379;
        }
        String url = "redis://" + redisProperties.getHost()
                + ":" + port;
        config.useSingleServer().setAddress(url) //单机
                .setPassword(redisProperties.getPassword())
                .setDatabase(redisProperties.getDatabase());
        //添加主从配置
        //config.useMasterSlaveServers().setMasterAddress("").setPassword("").addSlaveAddress(new String[]{"",""});
        //集群
        //config.useClusterServers().addNodeAddress(new String[]{"",""}).setPassword("");
        try {
            redissonClient = Redisson.create(config);
            return redissonClient;
        } catch (Exception e) {
            log.error("RedissonClient init redis url :[{}]",url,e);
            return null;
        }
    }

}

package com.common.redission;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Data
@Component
@ConfigurationProperties(prefix = "spring.redis")
public class RedisProperties {

    private String host;
    private int port;
    private String password;
    private int database;

}

使用AOP切面

package com.aa;
 

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

 
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface KrtLock {

    /**
     * 设置锁的名称
     *
     * @return
     */
    String lockName();

    /**
     * 设置多少秒钟自动关闭锁  单位:毫秒
     * @return
     */
    long leaveTime() default 30000;


    /**
     * 设置等待获取锁的时间
     * @return
     */
    long waitTime() default 60000;


}

package com.framework.aspect;

import com.krt.common.annotation.KrtLock;
import com.krt.common.bean.ReturnBean;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * @author 胡国坚
 * @date 2021/10/28 16:05
 * @description
 */
@Aspect
@Component
@Slf4j
public class KrtLockAspect {

    @Autowired
    private RedissonClient redissonClient;

    @Pointcut("@annotation(com.common.annotation.KrtLock)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        //组织机构配置注解
        //调用执行目标方法(result为目标方法执行结果)
        Object result = null;
        KrtLock krtLock = method.getAnnotation(KrtLock.class);
        String lockName = krtLock.lockName();
        long leaveTime = krtLock.leaveTime();
        long waitTime = krtLock.waitTime();

        RLock lock = redissonClient.getLock(lockName);
        try {
            boolean isLock = lock.tryLock(waitTime, leaveTime, TimeUnit.MILLISECONDS);
            if (!isLock) {
                return null;
            }
            result = joinPoint.proceed(args);
        } catch (InterruptedException e) {
            log.error("", e);
        } finally {
            if (lock.isLocked()) {
                lock.unlock();
            }
        }
        return result;
    }
}

   @Autowired
    private RedissonClient redissonClient;

    @KrtLock(lockName = "dsfosjidsds", leaveTime = 10000)
    public String aa() {
        String number = numberService.createNum("test123");
        System.err.println(number);
        return number;
    }

你可能感兴趣的:(spring,boot,redis,java)