spring boot如何集成redisson

集成及注意事项

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

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

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

手动注入redisson配置

一般情况下,生产环境都是有密码的。有密码的话,建议手动注入redisson配置,不用spring boot来帮你集成,因为可能spring boot识别不了密码。

  1. @Configurationpublic 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配置

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

登录后复制

利用锁的互斥策略,一开始这样的

  1. @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相同的代码。

注解方式

解决重复代码方式之一就是封装,在就是注解切面,想到注解方式更加灵活

于是

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

登录后复制

需要一个切面

  1. @Slf4j@Aspect@Component@RequiredArgsConstructorpublic 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();            }        }    }}

登录后复制

使用方法:

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

登录后复制

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

以上就是spring boot如何集成redisson的详细内容,更多请关注【创想鸟】其它相关文章!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
编程技术

springboot应用实例分析

2025-3-7 0:55:23

编程技术

SpringBoot中定时任务@Scheduled的多线程如何使用

2025-3-7 0:55:34

0 条回复 A文章作者 M管理员
欢迎您,新朋友,感谢参与互动!
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
私信列表
搜索