记录:401
场景:在Spring Boot微服务使用RedisTemplate的ValueOperations操作Redis String字符串。
版本:JDK 1.8,Spring Boot 2.6.3,redis-6.2.5
1.微服务中Redis配置信息
1.1在application.yml中Redis配置信息
spring:
redis:
host: 192.168.19.203
port: 28001
password: 12345678
timeout: 50000
1.2加载简要逻辑
Spring Boot微服务在启动时,自动注解机制会读取application.yml的注入到RedisProperties对象。在Spring环境中就能取到Redis相关配置信息了。
类全称:org.springframework.boot.autoconfigure.data.redis.RedisProperties
1.3在pom.xml添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.配置RedisTemplate
2.1配置RedisTemplate
@Configuration
public class RedisConfig {
@Bean("redisTemplate")
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
// 1.创建RedisTemplate对象
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
// 2.加载Redis配置
redisTemplate.setConnectionFactory(lettuceConnectionFactory);
// 3.配置key序列化
RedisSerializer<?> stringRedisSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringRedisSerializer);
redisTemplate.setHashKeySerializer(stringRedisSerializer);
// 4.配置Value序列化
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
ObjectMapper objMapper = new ObjectMapper();
objMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objMapper.activateDefaultTyping(objMapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objMapper);
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
// 5.初始化RedisTemplate
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@Bean
public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForValue();
}
}
2.2解析
在配置RedisTemplate后,在Spring环境中,可以@Autowired自动注入方式注入操作Redis对象。比如:RedisTemplate、ValueOperations。
3.使用ValueOperations操作Redis String字符串
3.1简要说明
使用ValueOperations操作字符串,常用操作:增、查、改、删、设置超时等。
3.2操作示例
@RestController
@RequestMapping("/hub/example/load")
@Slf4j
public class LoadController {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private ValueOperations valueOperations;
/**
* 操作String,使用ValueOperations
* 对应写命令: SET key value
* 对应读命令: GET key
*/
@GetMapping("/valueOperations")
public Object loadData02() {
log.info("ValueOperations操作开始...");
// 1.增
valueOperations.set("CityInfo:Hangzhou02", "杭州");
valueOperations.set("CityInfo:Hangzhou02", "苏州");
// 2.查
Object result01 = valueOperations.get("CityInfo:Hangzhou02");
log.info("result01 = " + result01.toString());
// 3.改
valueOperations.set("CityInfo:Hangzhou02", "杭州-西湖");
// 4.删
String result02 = (String) valueOperations.getAndDelete("CityInfo:Hangzhou02");
redisTemplate.delete("CityInfo:Hangzhou02");
// 5.1设置超时(方式一)
valueOperations.set("CityInfo:Hangzhou02", "杭州-西湖");
valueOperations.getAndExpire("CityInfo:Hangzhou02", 5, TimeUnit.MINUTES);
// 5.2设置超时(方式二)
valueOperations.set("CityInfo:Hangzhou02", "杭州-西湖");
redisTemplate.expire("CityInfo:Hangzhou02", 10, TimeUnit.MINUTES);
// 6.查询Value的字节大小
Long size =valueOperations.size("CityInfo:Hangzhou02");
System.out.println("缓存字节大小,size="+size +" bytes");
log.info("ValueOperations操作结束...");
return "执行成功";
}
}
3.3测试验证
使用Postman测试。
请求RUL:http://127.0.0.1:18205/hub-205-redis/hub/example/load/valueOperations
4.ValueOperations接口
4.1接口
ValueOperations是一个接口,默认实现类是DefaultValueOperations。
接口:org.springframework.data.redis.core.ValueOperations。
实现类:org.springframework.data.redis.core.DefaultValueOperations。
4.2接口源码
在源码中,查看接口具体方法,可以快速了解该接口具备功能,以便在生产中能根据实际场景对号入座找到合适方法解决实际问题。
public interface ValueOperations<K, V> {
void set(K key, V value);
void set(K key, V value, long timeout, TimeUnit unit);
default void set(K key, V value, Duration timeout) {
Assert.notNull(timeout, "Timeout must not be null!");
if (TimeoutUtils.hasMillis(timeout)) {
this.set(key, value, timeout.toMillis(), TimeUnit.MILLISECONDS);
} else {
this.set(key, value, timeout.getSeconds(), TimeUnit.SECONDS);
}
}
@Nullable
Boolean setIfAbsent(K key, V value);
@Nullable
Boolean setIfAbsent(K key, V value, long timeout, TimeUnit unit);
@Nullable
default Boolean setIfAbsent(K key, V value, Duration timeout) {
Assert.notNull(timeout, "Timeout must not be null!");
return TimeoutUtils.hasMillis(timeout) ? this.setIfAbsent(key, value, timeout.toMillis(), TimeUnit.MILLISECONDS) : this.setIfAbsent(key, value, timeout.getSeconds(), TimeUnit.SECONDS);
}
@Nullable
Boolean setIfPresent(K key, V value);
@Nullable
Boolean setIfPresent(K key, V value, long timeout, TimeUnit unit);
@Nullable
default Boolean setIfPresent(K key, V value, Duration timeout) {
Assert.notNull(timeout, "Timeout must not be null!");
return TimeoutUtils.hasMillis(timeout) ? this.setIfPresent(key, value, timeout.toMillis(), TimeUnit.MILLISECONDS) : this.setIfPresent(key, value, timeout.getSeconds(), TimeUnit.SECONDS);
}
void multiSet(Map<? extends K, ? extends V> map);
@Nullable
Boolean multiSetIfAbsent(Map<? extends K, ? extends V> map);
@Nullable
V get(Object key);
@Nullable
V getAndDelete(K key);
@Nullable
V getAndExpire(K key, long timeout, TimeUnit unit);
@Nullable
V getAndExpire(K key, Duration timeout);
@Nullable
V getAndPersist(K key);
@Nullable
V getAndSet(K key, V value);
@Nullable
List<V> multiGet(Collection<K> keys);
@Nullable
Long increment(K key);
@Nullable
Long increment(K key, long delta);
@Nullable
Double increment(K key, double delta);
@Nullable
Long decrement(K key);
@Nullable
Long decrement(K key, long delta);
@Nullable
Integer append(K key, String value);
@Nullable
String get(K key, long start, long end);
void set(K key, V value, long offset);
@Nullable
Long size(K key);
@Nullable
Boolean setBit(K key, long offset, boolean value);
@Nullable
Boolean getBit(K key, long offset);
@Nullable
List<Long> bitField(K key, BitFieldSubCommands subCommands);
RedisOperations<K, V> getOperations();
}
以上,感谢。
2023年4月12日