一、使用StringRedisTemplate实现分布式锁
package com.example.baidu.redis; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.UUID; import java.util.concurrent.TimeUnit; @RestController public class RedisController { @Autowired private RedisTemplate<String, String> redisTemplate; @Autowired private StringRedisTemplate stringRedisTemplate; @GetMapping("/redis") public void sendMessage(@RequestParam String message) { String clientId = UUID.randomUUID().toString(); Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(message, clientId, 10, TimeUnit.SECONDS); if (!result) { System.out.println("获取锁失败!"); } else { try { Thread.sleep(100000); } catch (InterruptedException e) { ; e.printStackTrace(); } finally { if (clientId.equals(stringRedisTemplate.opsForValue().get(message))) { stringRedisTemplate.delete(message); } } } } }
package com.example.baidu.redis; import org.redisson.Redisson; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.concurrent.TimeUnit; @Controller public class RedissonController { @GetMapping("/redisson") @ResponseBody public int redisson() { testThreadLock(); return 0; } @Autowired private RedissonClient redissonClient; @Autowired private Redisson redisson; public void lock(String key, String num) { //获取锁 RLock lock = redisson.getLock(key); boolean locked = false; try { //设置锁 locked = lock.tryLock(10, TimeUnit.SECONDS); //locked = lock.lock(); if (locked) { //开始写业务 System.out.println(num + "锁住了。。。"); System.out.println(num + "模拟业务耗时开始。。"); Thread.sleep(10); System.out.println(num + "模拟业务耗时结束。。。"); } else { System.out.println(num + "没锁住。。。"); } } catch (Exception e) { e.printStackTrace(); } finally { if (locked) { System.out.println(num + "释放锁"); System.out.println(); lock.unlock(); } } } public void testThreadLock() { String key = "threadLock"; for (int i = 1; i < 100; i++) { new Thread() { @Override public void run() { lock("test", this.getName()); } }.start(); } } }