1. Introduce the jar package of redisson through maven
<dependency> <groupId>org.redisson</groupId> <artifactId>redisson</artifactId> <version>3.6.5</version> </dependency>
2. Introduce the relevant configuration of redis in the yaml file (redis single node can read the original redis configuration assembly, if it is the master and slave needs to be configured separately, the relevant properties can refer to org.redisson.config.Config.masterSlaveServersConfig)
spring: say again: host: 127.0.0.1 port: 6379 password: 111111
3. Add springboot configuration
package com.aoxun.config; import org.redisson.Redisson; import org.redisson.api.RedissonClient; import org.redisson.config.Config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * redisson configuration * Currently using Tencent Cloud's single-node redis, so temporarily configure a single service * * */ @Configuration public class RedissonConfig { @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private String port; @Value("${spring.redis.password}") private String password; @Bean public RedissonClient getRedisson(){ Config config = new Config(); config.useSingleServer().setAddress("redis://" + host + ":" + port).setPassword(password); //添加主从配置 // config.useMasterSlaveServers().setMasterAddress("").setPassword("").addSlaveAddress(new String[]{"",""}); return Redisson.create(config); } }
Fourth, inject RedissonClient where you need to use it
package com.aoxun.modular.menjin.service.impl; import java.util.concurrent.TimeUnit; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class TestRedissonLock{ @Autowired private RedissonClient redissonClient; public void cameraCallback () { RLock rlock = redissonClient.getLock("redisson:lock:personId" + 123 );
//Set the lock timeout to prevent abnormal deadlocks rlock.lock(20, TimeUnit.SECONDS); try { // Execute business logic Thread.sleep(10000 ); System.out.println(123); } catch(Exception e){ }finally{ rlock.unlock(); } } }
At this point, the simple example of using redisson to implement distributed locks has ended