首頁  >  文章  >  Java  >  spring boot如何整合redisson

spring boot如何整合redisson

PHPz
PHPz轉載
2023-05-14 19:46:191700瀏覽

整合及注意事項

redisson支援redis環境,單機、叢集、哨兵、雲端等。

這裡就講一下叢集模式要注意的地方,redisson啟動會偵測master/slave節點是否正常,一般來說3分片3主3從是沒有什麼問題的,但是如果測試環境1分片1主1從或3主都是啟動不了的。

除了環境要注意,還有註意相容有無密碼的情況。

手動注入redisson配置

一般情況下,生產環境都是有密碼的。有密碼的話,建議手動注入redisson配置,不用spring boot來幫你集成,因為可能spring boot識別不了密碼。

@Configuration
public class RedissonConfiguration {
    @Value("${spring.redis.cluster.nodes}")
    private String node;
    @Value("${spring.redis.password:}")
    private String password;
    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        String[] nodes = node.split(",");
        ClusterServersConfig clusterServersConfig = config.useClusterServers();
        for (String nodeAddress : nodes) {
            clusterServersConfig.addNodeAddress(prefixAddress(nodeAddress));
        }
        if (StringUtils.isNotBlank(password)) {
            clusterServersConfig.setPassword(password);
        }
        return Redisson.create(config);
    }
    private String prefixAddress(String address) {
        if (!StringUtils.isBlank(address) && !address.startsWith("redis")) {
            return "redis://" + address;
        }
        return address;
    }
}

上面可以依照自己實際狀況調優一些配置。

當然除了密碼要注意,還有一點就是有沒有ssl,目前所在company是用的亞馬遜雲,會有ssl

spring boot 相容redis 可以在yaml配置里天際: Ssl:true,但對於redisson來說添加前綴就可以啦:

rediss:// ip:端口或域名

具體yaml配置

spring:
  redis:
    cluster:
      nodes: rediss://clustercfg.xxx
    password: 'xxx'
    timeout: 30000
    Ssl: true
    lettuce:
      pool:
        max-idle: 100

利用鎖的互斥策略,一開始這樣的

@Scheduled(cron = "${xxx:0 0 */2 * * ?}")
public void createProcess() {
    RLock lock = redisson.getLock(key);
    try {
        if (lock.tryLock()) {
           // 执行运行程序
        } else {
            log.info("createProcess 获取锁失败");
        }
    } catch (Exception e) {
        log.error("xxx", e);
    } finally {
        // 是否有锁 && 是否当前线程
        if (lock != null && lock.isLocked() && lock.isHeldByCurrentThread()) {
            lock.unlock();
        }
    }
}

咋一看是沒有什麼問題的,但是本次重構的定時任務比較多,因此會涉及到很多try catch相同的程式碼。

註解方式

解決重複程式碼方式之一就是封裝,在是註解切面,想到註解方式更有彈性

於是

/**
 * Redisson 同步锁
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface RedissonSyncLock {
    String pref();
    /**
     * 锁后缀,一般前缀根据业务来定,后缀是具体的场景
     */
    String keyEL();
    /**
     * 等待时长 【需要区分是互斥还是阻塞,互斥默认0就可以】
     */
    int waitSec() default 0;
}

需要一個切面

@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class RedissonSyncLockAspect {
    private final Redisson redisson;
    @Around(value = "@annotation(xxx.RedissonSyncLock)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        RedissonSyncLock redissonSyncLock = signature.getMethod().getAnnotation(RedissonSyncLock.class);
        Object[] args = joinPoint.getArgs();
        String key = SpelUtil.parseSpel(signature.getMethod(), args, redissonSyncLock.keyEL());
        RLock lock = null;
        try {
            if (StringUtils.isNotBlank(key) && !StringUtils.equals(key, "null") 
                lock = redisson.getLock(redissonSyncLock.pref().concat(key));
                if (lock.tryLock(redissonSyncLock.waitSec(), TimeUnit.SECONDS)) {
                    return joinPoint.proceed();
                }
            }
            log.info("RedissonSyncLockAspect 上锁失败 {}", key);
        } finally {
            if (lock != null && lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }
}

使用方法:

@RedissonSyncLock(pref = KeyConstant.xxx, keyEL = "#bean.accountNo")
private void xxx(Bean bean){
     // 程序执行
}

的確使用起來是比較方便的。

以上是spring boot如何整合redisson的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除