Redisson配置类
/** * @author hwq * @date 2019/05/02 ** RedissonManager类 *
*/@Slf4j@Componentpublic class RedissonManager { private Config config = new Config(); private Redisson redisson = null;public Redisson getRedisson() { return redisson;}private static String redis1Ip = PropertiesUtil.getProperty("redis1.ip");private static Integer redis1Port = Integer.parseInt(PropertiesUtil.getProperty("redis1.port"));private static String redis2Ip = PropertiesUtil.getProperty("redis2.ip");private static Integer redis2Port = Integer.parseInt(PropertiesUtil.getProperty("redis2.port"));@PostConstructprivate void init() { try { config.useSingleServer().setAddress(new StringBuilder().append(redis1Ip).append(":").append(redis1Port).toString()); redisson = (Redisson) Redisson.create(config); log.info("初始化Redisson结束"); } catch (Exception e) { log.error("redisson init error", e); }}}复制代码
properties文件中的配置
redis.ip1=127.0.0.1 redis.port1=6379 redis.ip2=127.0.0.1 redis.port2=6380复制代码
Pom.xml文件中需要引入的
org.redisson redisson 2.9.0 复制代码 com.fasterxml.jackson.dataformat jackson-dataformat-avro 2.9.0
代码实现:
@Scheduled(cron = "0 */1 * * * ?")//每一分钟执行一次 public void closeOrderTaskV4() { log.info("关闭订单任务开启"); RLock lock = redissonManager.getRedisson().getLock(Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK); boolean getLock = false; try { if (getLock = lock.tryLock(0, 50, TimeUnit.SECONDS)) { log.info("Redisson获取到分布式锁:{},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("Redisson没有获取到分布式锁:{},ThreadName:{}", Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK, Thread.currentThread().getName()); } } catch (InterruptedException e) { log.error("Redisson分布式锁获取异常", e); } finally { if (!getLock) { return; } lock.unlock(); log.info("Redisson分布式锁释放锁"); } log.info("关闭订单任务结束"); }复制代码