iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >springboot优雅集成redisson详解
  • 551
分享到

springboot优雅集成redisson详解

springboot集成redissonspringbootredisson 2022-11-13 19:11:56 551人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

目录集成及注意事项手动注入Redisson配置具体yaml配置注解方式需要一个切面集成及注意事项 上一篇文章大白话说了一下redisson的可重入、可续约、阻塞、时间轮、红锁、联锁、

集成及注意事项

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

拔剑起蒿莱????

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

注解方式

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

于是


@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface RedissonSyncLock {
    String pref();
    
    String keyEL();
    
    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详解的详细内容,更多关于spring boot集成redisson的资料请关注编程网其它相关文章!

--结束END--

本文标题: springboot优雅集成redisson详解

本文链接: https://www.lsjlt.com/news/170559.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作