说一说spring boot优雅集成redisson

2,559 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第3天,点击查看活动详情

【熬夜打卡】上一篇文章大白话说了一下redisson的可重入、可续约、阻塞、时间轮、红锁、联锁、加锁逻辑和解锁逻辑,如果大家有兴趣先看上一篇,直通车

拔剑起蒿莱👥👥👥👥

今天简单说一下集成及注意事项。

redisson支持redis环境,单机、集群、哨兵、云等。

这里就讲一下集群模式需要注意的地方,redisson启动会检测master/slave节点是否正常,一般来说3分片3主3从是没有什么问题的,但是如果测试环境1分片1主1从或者3主都是启动不了的。

除了环境需要注意,还有注意兼容有无密码的情况。

一般情况下,生产环境都是有密码的。有密码的话,建议手动注入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){
     // 程序执行
}

的确使用起来是比较方便的。

写了这么多,下一篇讲一讲 是否与 StringRedisTemplate 是否兼容?


及时当勉励 岁月不待人

能看到这里的人呀,都是菁英。❤❤️❤️❤️❤

非常感谢

菁英们能看到这里,如果这个文章写得还不错,觉得有点东西的话 求点赞👍 求关注❤️ 求分享👥 对需要持续更新的我来说真的 非常有用!!

如果本篇博客有任何错误,请批评指教,不胜感激 !

文末福利,最近整理一份面试资料《Java面试通关手册》,覆盖了Java核心技术、JVM、Java并发、SSM、微服务、数据库、数据结构等等。获取方式:【别卷了大兄弟】