1.增長依賴java
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>2.9.0</version>
</dependency>
<!--com.fasterxml.jackson.dataformat.avro.PackageVersion-->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-avro</artifactId>
<version>2.9.0</version>
</dependency>redis
2.初始化redissionspring
import lombok.extern.slf4j.Slf4j; import org.redisson.Redisson; import org.redisson.config.Config; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @Slf4j @Component public class RedissonManager { //redisson支持單實例模式,不支持分佈式 private Config config = new Config(); private Redisson redisson = null; private final static String redis1Ip = PropertiesUtil.getProperty("redis1.ip"); private final static Integer redis1Port = Integer.parseInt(PropertiesUtil.getProperty("redis1.port")); //注入到Spring容器的話,使用@PostConstruct或者靜態塊初始化,效果是同樣的{} @PostConstruct private void init() { try { ////127.0.0.1:6379 // config.useSingleServer().setAddress(new StringBuilder().append(redis1Ip).append(":").append(redis1Port).toString()); //單主模式 // config.useMasterSlaveServers().setMasterAddress(new StringBuilder().append(redis1Ip).append(":").append(redis1Port).toString()); //主從模式 // config.useMasterSlaveServers().setMasterAddress("127.0.0.1:6379").addSlaveAddress("127.0.0.1:6380"); // redisson = (Redisson) Redisson.create(config); log.info("初始化Redisson結束"); } catch (Exception e) { log.error("redisson init error", e); } } // { // init(); // } public Redisson getRedisson() { return redisson; } }
3.使用app
/** * Redisson分佈式鎖實現 * @throws InterruptedException */ // @Scheduled(cron="0 */1 * * * ?")//每1分鐘(每一個1分鐘的整數倍) public void closeOrderTaskV4() throws InterruptedException { RLock lock = redissonManager.getRedisson().getLock(Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK); boolean getLock = false; try { if(getLock = lock.tryLock(2,5, TimeUnit.SECONDS)){//trylock增長鎖 log.info("===獲取{},ThreadName:{}",Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK,Thread.currentThread().getName()); int hour = Integer.parseInt(PropertiesUtil.getProperty("close.order.task.time.hour","2")); iOrderService.closeOrder(hour); }else{ log.info("===沒有得到分佈式鎖:{}",Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK); } }finally { if(!getLock){ return; } log.info("===釋放分佈式鎖:{}",Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK); lock.unlock(); } }