记录: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.203port: 28001password: 12345678timeout: 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.初始化RedisTemplateredisTemplate.afterPropertiesSet();return redisTemplate;}@Beanpublic 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 {@Autowiredprivate RedisTemplate redisTemplate;@Autowiredprivate 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);}}@NullableBoolean setIfAbsent(K key, V value);@NullableBoolean setIfAbsent(K key, V value, long timeout, TimeUnit unit);@Nullabledefault 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);}@NullableBoolean setIfPresent(K key, V value);@NullableBoolean setIfPresent(K key, V value, long timeout, TimeUnit unit);@Nullabledefault 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);@NullableBoolean multiSetIfAbsent(Map<? extends K, ? extends V> map);@NullableV get(Object key);@NullableV getAndDelete(K key);@NullableV getAndExpire(K key, long timeout, TimeUnit unit);@NullableV getAndExpire(K key, Duration timeout);@NullableV getAndPersist(K key);@NullableV getAndSet(K key, V value);@NullableList<V> multiGet(Collection<K> keys);@NullableLong increment(K key);@NullableLong increment(K key, long delta);@NullableDouble increment(K key, double delta);@NullableLong decrement(K key);@NullableLong decrement(K key, long delta);@NullableInteger append(K key, String value);@NullableString get(K key, long start, long end);void set(K key, V value, long offset);@NullableLong size(K key);@NullableBoolean setBit(K key, long offset, boolean value);@NullableBoolean getBit(K key, long offset);@NullableList<Long> bitField(K key, BitFieldSubCommands subCommands);RedisOperations<K, V> getOperations();
}
以上,感谢。
2023年4月12日