内容纲要
整合Springboot + Redis
使用Springboot快速整合Redis,Redisson
1.导入Redis相关依赖
<!-- Redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- https://github.com/redisson/redisson#quick-start -->
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.17.5</version>
</dependency>
2. 在Springboot配置文件中配置Redis连接
# Redis
redis:
host: ServerUrl
port:
password:
lettuce:
pool:
max-active: 8
max-idle: 8
max-wait: -1ms
min-idle: 0
timeout: 3000
database: 0 # 指定几号数据库
3. 配置RedisTemplate
数据传输过程中涉及序列化问题,如果不主动指定序列化器,可能会发生因为序列化不同而造成的问题(乱码或直接报错)。
/**
* Redis配置类
*
* @author gaffey
*
*/
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
//string
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
//Hash
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());
return template;
}
}
3.配置Redisson连接
Redisson可以看作是一个Redis的客户端,是封装了的框架。可以按照Java的语法习惯直接操作Redis。同时它还实现了分布式锁框架,可使用Redisson实现分布式锁。
/**
* Redisson配置类
*
* @author GaffEy
*/
@Configuration
@ConfigurationProperties(prefix = "spring.redis")
@Data
public class RedissionConfig {
private String host;
private String port;
@Bean
public RedissonClient redissonClient() {
// 1. 创建配置
Config config = new Config();
String redisAddress = String.format("redis://%s:%s", host, port);
config.useSingleServer()
.setPassword("password") // 即auth password
.setAddress(redisAddress)
.setDatabase(3);
// 2. 创建实例
RedissonClient redisson = Redisson.create(config);
return redisson;
}
}
Redis + Lua脚本
// Lua脚本
private static final String luaScript = "local zsetKey = KEYS[1]\n" +
"local attractionName = ARGV[1]\n" +
"local decreasedScore = tonumber(ARGV[2])\n" +
"redis.call('ZREM', zsetKey, attractionName)\n" +
"redis.call('ZADD', zsetKey, decreasedScore, attractionName)\n" +
"return 'True'";
public void decreaseHot(){
List<String> attractionNameList = attractionMapper.selectAttractionName();
Set<ZSetOperations.TypedTuple<Object>> tuples = redisTemplate.opsForZSet().rangeWithScores(RedisUtils.ZSET_KEY, 0, -1);
for (ZSetOperations.TypedTuple<Object> tuple:tuples){
String attractionName = tuple.getValue().toString();
Double score = Double.valueOf(tuple.getScore().toString());
Double decreasedScore = score * 0.8;
String newScore = String.valueOf(decreasedScore);
RedisScript<Object> script = new DefaultRedisScript<>(luaScript, Object.class);
stringRedisTemplate.execute(script, Collections.singletonList(RedisUtils.ZSET_KEY),attractionName,newScore);
}
}
使用Lua脚本时一定要注意序列化问题,通过
Lua
脚本存入,存入的Value
是通过new StringRedisSerializer()
序列化器序列化为字符串类型。注意自己RedisTmplae
配置的ValueSerializer()
要配置成StringRedisSerializer()
,否则传输数据会出错。最好的方法是单独配置一个
RedisTemplate