1,导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.13.6</version>
</dependency>
2,添加配置
spring:
redis:
host: 127.0.0.1
port: 6379
cluster:
nodes:
- localhost:7939
- localhost:7940
- localhost:7941
添加redisTemplate配置
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory connectionFactory){
RedisTemplate<String,Object> template=new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
GenericJackson2JsonRedisSerializer jsonRedisSerializer=new GenericJackson2JsonRedisSerializer();
template.setKeySerializer(RedisSerializer.string());
template.setHashKeySerializer(RedisSerializer.string());
template.setValueSerializer(jsonRedisSerializer);
template.setHashValueSerializer(jsonRedisSerializer);
return template;
}
}
使用redis:
@Resource
private RedisTemplate<String,String> redisTemplate;
@GetMapping("/set")
public void set(@RequestParam("key") String key,@RequestParam("value") String value){
redisTemplate.opsForValue().set(key,value,10, TimeUnit.SECONDS);
}
@GetMapping("/get")
public String get(@RequestParam("key") String key){
String value=redisTemplate.opsForValue().get(key);
System.out.println(value);
return value;
}
使用redission分布式锁:
@Resource
private RedissonClient redissonClient;
public void lock(String key) {
RLock lock = redissonClient.getLock(key);
try {
//获取到锁
if (lock.tryLock(0, 5, TimeUnit.MILLISECONDS)) {
// 执行业务逻辑
} else {
//重试n次
Thread.sleep(1000);
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
if (lock.isLocked()) {
if (lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}
}
使用红锁
RLock lock = redissonClient.getLock(key);
// 对普通锁包装一层
RedissonRedLock redissonRedLock=new RedissonRedLock(lock);