配置地址:
redisson: # redis服务地址 如果集群使用","进行分割 server-address: redis://${spring.redis.host}:${spring.redis.port} database: ${spring.redis.database}
创建配置类:
@configurationproperties(prefix = "redisson") @configuration public class redissonconfig { /** redis服务地址 如果集群使用","进行分割 */ private string serveraddress; private integer database; public string getserveraddress() { return serveraddress; } public void setserveraddress(string serveraddresss) { this.serveraddress = serveraddresss; } public integer getdatabase() { return database; } public void setdatabase(integer database) { this.database = database; } }
注册redission bean:
/** * redissonclient * @return */ @bean public redissonclient redissonclient(){ string splitchar = ","; string serveraddress = redissonconfig.getserveraddress(); string[] serveraddressarr = serveraddress.split(splitchar); config config = new config(); if (serveraddressarr.length == 1) { //单例redis config.usesingleserver() .setaddress(redissonconfig.getserveraddress()) .setdatabase(redissonconfig.getdatabase()); } else { //集群redis config.useclusterservers().addnodeaddress(serveraddressarr); } return redisson.create(config); }
防止重复初始化:
** * 初始化告警统计记录 保证告警统计不会被重复初始化 * * @param areaid 部门id * @throws bizexception */ public void initwarningstatisticssafe(string areaid) throws bizexception { //创建锁名称 string lockname = generateinitwarningstatisticslockname(areaid); rlock lock = redisclient.getlock(lockname); try { //尝试获取锁 (最多尝试10秒,获取到后15秒后释放锁) boolean isacquirelock = lock.trylock(10, 15, timeunit.seconds); if (!isacquirelock) { logger.error("初始化消息统计 --- 获取锁失败 lockname = " + lockname); throw new bizexception("系统异常"); } else { try { //查询【告警统计】 (能够查询到最新的数据,因为默认隔离级别是read committed list<warningstatisticspo> warningstatisticspos = warningstatisticsdao.selectbyarea(areaid); if (collectionutils.isempty(warningstatisticspos)) { //如果部门不存在告警统计,才进行初始化 initwarningstatistics()会开启一个新事务 warningstatisticsservice.initwarningstatistics(areaid); } } finally { //释放锁 (在事务提交后才释放锁。保证其它事务在获取锁后能查询到数据,不会再进行初始化。) lock.unlock(); } } } catch (interruptedexception e) { e.printstacktrace(); } }
到此这篇关于redission分布式锁防止重复初始化问题的文章就介绍到这了,更多相关redission分布式锁内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!