引入 Redisson 即可 ,会自动帮我们续期
RedissonClient 和 Redisson 引入一个即可,和版本有关
实现逻辑如下;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| public class GrabRedisRedissonServiceImpl implements GrabService {
@Autowired RedissonClient redissonClient;
@Autowired OrderService orderService; @Override public String grabOrder(int orderId , int driverId){ String lock = "order_"+(orderId+""); RLock rlock = redissonClient.getLock(lock.intern()); try { rlock.lock(); try { TimeUnit.MINUTES.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("司机:"+driverId+" 执行抢单逻辑"); boolean b = orderService.grab(orderId, driverId); if(b) { System.out.println("司机:"+driverId+" 抢单成功"); }else { System.out.println("司机:"+driverId+" 抢单失败"); } } finally { rlock.unlock(); } return null; } }
|
Redis 配置类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| @Component public class RedisConfig { @Bean public RedissonClient redissonClient() { Config config = new Config(); config.useSingleServer().setAddress("127.0.0.1:6379").setDatabase(0);
return Redisson.create(config); }
}
|