Records : 400
Scenario : Use RedisTemplate to operate Redis cache and queue in Spring Boot microservices. Use ValueOperations to operate Redis String; use ListOperations to operate Redis List, use HashOperations to operate Redis Hash, use SetOperations to operate Redis Set collection (unordered collection), use ZSetOperations to operate Redis Zset (ordered collection).
Versions : JDK 1.8, Spring Boot 2.6.3, redis-6.2.5
1. Redis configuration information in microservices
1.1 Redis configuration information in application.yml
spring:
redis:
host: 192.168.19.203
port: 28001
password: 12345678
timeout: 50000
1.2 Load brief logic
When the Spring Boot microservice starts, the automatic annotation mechanism will read application.yml and inject it into the RedisProperties object. Redis-related configuration information can be obtained in the Spring environment.
Full class name: org.springframework.boot.autoconfigure.data.redis.RedisProperties
1.3 Add dependencies in pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2. Configure RedisTemplate
2.1 Configure 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();
}
@Bean
public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForList();
}
@Bean
public HashOperations<String, Object, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForHash();
}
@Bean
public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForSet();
}
@Bean
public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForZSet();
}
}
2.2 Analysis
After configuring the RedisTemplate, in the Spring environment, the @Autowired automatic injection method can be used to inject and operate the Redis object. For example: RedisTemplate, ValueOperations, ListOperations, HashOperations, SetOperations, ZSetOperations.
3. Directly use RedisTemplate operation
3.1 Brief description
Use the boundValueOps method of RedisTemplate to operate strings, common operations: add, check, modify, delete, set timeout, etc.
3.2 Operation example
@RestController
@RequestMapping("/hub/example/load")
@Slf4j
public class LoadController {
@Autowired
private RedisTemplate redisTemplate;
/**
* 操作缓存方式,直接使用RedisTemplate
* 对应写命令: SET key value
* 对应读命令: GET key
*/
@GetMapping("/redisTemplate")
public Object loadData01() {
log.info("RedisTemplate操作开始...");
// 1.增
redisTemplate.boundValueOps("CityInfo:Hangzhou01").set("杭州");
// 2.查
Object result01 = redisTemplate.boundValueOps("CityInfo:Hangzhou01").get();
log.info("result01 = " + result01.toString());
// 3.改
redisTemplate.boundValueOps("CityInfo:Hangzhou01").set("杭州-西湖");
// 4.删
redisTemplate.delete("CityInfo:Hangzhou01");
// 5.1设置超时(方式一)
redisTemplate.boundValueOps("CityInfo:Hangzhou01").set("杭州-西湖");
redisTemplate.expire("CityInfo:Hangzhou01", 5, TimeUnit.MINUTES);
// 5.2设置超时(方式二)
redisTemplate.boundValueOps("CityInfo:Hangzhou01-01").set("杭州", 5, TimeUnit.MINUTES);
log.info("RedisTemplate操作结束...");
return "执行成功";
}
}
3.3 Test verification
Use Postman test.
Request RUL: http://127.0.0.1:18205/hub-205-redis/hub/example/load/redisTemplate
4. Use ValueOperations to operate Redis String
4.1 Brief description
Use ValueOperations to manipulate strings, common operations: add, check, modify, delete, set timeout, etc.
4.2 Operation example
@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 "执行成功";
}
}
4.3 Test Verification
Use Postman test.
Request RUL: http://127.0.0.1:18205/hub-205-redis/hub/example/load/valueOperations
5. Use ListOperations to operate the Redis List list
5.1 Brief description
Use the ListOperationsRedis List list, common operations: add, check, delete, set timeout, etc.
5.2 Operation example
@RestController
@RequestMapping("/hub/example/load")
@Slf4j
public class LoadController {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private ListOperations listOperations;
/**
* 操作List,使用ListOperations
* 对应写命令: LPUSH 队列名称 值
* 对应读命令: LPOP 队列名称
* 对应写命令: RPUSH 队列名称 值
* 对应读命令: RPOP 队列名称
*/
@GetMapping("/listOperations")
public Object loadData03() {
log.info("ListOperations操作开始...");
// 1.增
listOperations.leftPush("CityInfo:Hangzhou03", "杭州");
listOperations.rightPush("CityInfo:Hangzhou03", "苏州");
// 2.查,查出队列指定范围元素,不会删除队列里面数据,(0,-1)查出全部元素
listOperations.leftPush("CityInfo:Hangzhou03", "杭州");
listOperations.leftPush("CityInfo:Hangzhou03", "苏州");
List cityList = redisTemplate.boundListOps("CityInfo:Hangzhou03").range(0, -1);
cityList.forEach((value)->{
System.out.println("value="+value);
});
// 3.取,逐个取出队列元素(取出一个元素后,队列就没有这个元素了)
Object city01 = listOperations.leftPop("CityInfo:Hangzhou03");
Object city02 = listOperations.rightPop("CityInfo:Hangzhou03");
log.info("city01=" + city01 + ",city02=" + city02);
// 4.删
listOperations.leftPush("CityInfo:Hangzhou03", "杭州");
listOperations.leftPush("CityInfo:Hangzhou03", "苏州");
redisTemplate.delete("CityInfo:Hangzhou03");
// 5.设置超时
listOperations.leftPush("CityInfo:Hangzhou03", "上海");
redisTemplate.boundValueOps("CityInfo:Hangzhou03").expire(5, TimeUnit.MINUTES);
redisTemplate.expire("CityInfo:Hangzhou03", 10, TimeUnit.MINUTES);
// 6.查询List的元素个数
Long size =listOperations.size("CityInfo:Hangzhou03");
System.out.println("查询List的元素个数,size="+size);
log.info("ListOperations操作结束...");
return "执行成功";
}
}
5.3 Test verification
Use Postman test.
Request RUL: http://127.0.0.1:18205/hub-205-redis/hub/example/load/listOperations
6. Use HashOperations to operate Redis Hash hash
6.1 Brief description
Use HashOperations to operate Redis Hash hashes, common operations: add, check, modify, delete, set timeout, etc.
6.2 Operation example
@RestController
@RequestMapping("/hub/example/load")
@Slf4j
public class LoadController {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private HashOperations hashOperations;
/**
* 操作Hash,使用HashOperations
* 对应写命令: HMSET
* 对应读命令: HGETALL
* 本质就是在一个key对应存储了一个Map
*/
@GetMapping("/hashOperations")
public Object loadData04() {
log.info("HashOperations操作开始...");
// 1.增
hashOperations.put("CityInfo:Hangzhou04", "hangzhou", "杭州");
hashOperations.put("CityInfo:Hangzhou04", "suzhou", "苏州");
// 2.1查-获取map键值对数据
Map resultMap = hashOperations.entries("CityInfo:Hangzhou04");
resultMap.forEach((key, value) -> {
System.out.println("key=" + key + ",value=" + value);
});
// 2.2查-获取Map的全部key
Set set = hashOperations.keys("CityInfo:Hangzhou04");
set.forEach((key) -> {
System.out.println("key=" + key);
});
// 2.3查-获取Map的全部value
List list = hashOperations.values("CityInfo:Hangzhou04");
list.forEach((value) -> {
System.out.println("value=" + value);
});
// 3.改
hashOperations.put("CityInfo:Hangzhou04", "hangzhou", "杭州-西湖");
// 4.1删,(删除指定值)
hashOperations.delete("CityInfo:Hangzhou04", "hangzhou", "suzhou");
// 4.2删,(删除全部)
redisTemplate.delete("CityInfo:Hangzhou04");
// 5.设置超时
hashOperations.put("CityInfo:Hangzhou04", "hangzhou", "杭州");
redisTemplate.boundValueOps("CityInfo:Hangzhou04").expire(5, TimeUnit.MINUTES);
redisTemplate.expire("CityInfo:Hangzhou04", 10, TimeUnit.MINUTES);
// 6.查询Hash的元素个数
Long size =hashOperations.size("CityInfo:Hangzhou04");
System.out.println("查询Hash的元素个数,size="+size);
log.info("HashOperations操作结束...");
return "执行成功";
}
}
6.3 Test Verification
Use Postman test.
Request RUL: http://127.0.0.1:18205/hub-205-redis/hub/example/load/hashOperations
7. Use SetOperations to operate the Redis Set collection (unordered collection)
7.1 Brief description
Use SetOperations to operate the Redis Set collection (unordered collection), common operations: add, check, delete, set timeout, etc.
7.2 Operation Example
@RestController
@RequestMapping("/hub/example/load")
@Slf4j
public class LoadController {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private SetOperations setOperations;
/**
* 操作ZSet,使用ZSetOperations,有序排列且无重复数据
* 对应写命令: ZADD
* 对应读命令: SPOP
*/
@GetMapping("/zSetOperations")
public Object loadData06() {
log.info("ZSetOperations操作开始...");
// 1.增
zSetOperations.add("CityInfo:Hangzhou06", "杭州", 20);
zSetOperations.add("CityInfo:Hangzhou06", "苏州", 10);
zSetOperations.add("CityInfo:Hangzhou06", "上海", 30);
zSetOperations.add("CityInfo:Hangzhou06", "北京", 101);
zSetOperations.add("CityInfo:Hangzhou06", "宁波", 999);
// 2.1查(通过下标查值,从0开始取第一个值)
Set set = zSetOperations.range("CityInfo:Hangzhou06", 1, 4);
set.forEach((value) -> {
System.out.println("value=" + value);
});
// 2.2查(通过Score查值)
set = zSetOperations.rangeByScore("CityInfo:Hangzhou06", 29, 60);
set.forEach((value) -> {
System.out.println("value=" + value);
});
// 3.改
zSetOperations.add("CityInfo:Hangzhou06", "杭州", 99);
// 4.1取(取出Score最大的值,取出后队列中值会删除)
ZSetOperations.TypedTuple obj1 = zSetOperations.popMax("CityInfo:Hangzhou06");
System.out.println("取出最大值,value=" + obj1.getValue() + ",Score=" + obj1.getScore());
// 4.2取(取出Score最小的值,取出后队列中值会删除)
ZSetOperations.TypedTuple obj2 = zSetOperations.popMin("CityInfo:Hangzhou06");
System.out.println("取出最小值,value=" + obj2.getValue() + ",Score=" + obj2.getScore());
// 5.1删除指定值
zSetOperations.remove("CityInfo:Hangzhou06", "上海");
// 5.2按照Score分数大小删除
zSetOperations.removeRangeByScore("CityInfo:Hangzhou06", 1, 100);
// 5.3删(删除全部)
redisTemplate.delete("CityInfo:Hangzhou06");
// 6.设置超时
zSetOperations.add("CityInfo:Hangzhou06", "杭州", 21);
zSetOperations.add("CityInfo:Hangzhou06", "苏州", 11);
redisTemplate.boundValueOps("CityInfo:Hangzhou06").expire(5, TimeUnit.MINUTES);
redisTemplate.expire("CityInfo:Hangzhou06", 10, TimeUnit.MINUTES);
// 7.查询ZSet的元素个数
Long size =zSetOperations.size("CityInfo:Hangzhou06");
System.out.println("查询ZSet的元素个数,size="+size);
log.info("ZSetOperations操作结束...");
return "执行成功";
}
}
7.3 Test verification
Use Postman test.
Request RUL: http://127.0.0.1:18205/hub-205-redis/hub/example/load/setOperations
8. Use ZSetOperations to operate Redis Zset (ordered collection)
8.1 Brief description
Use ZSetOperations to operate Redis Zset (ordered collection), common operations: add, check, modify, delete, set timeout, etc.
8.2 Operation example
@RestController
@RequestMapping("/hub/example/load")
@Slf4j
public class LoadController {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private ZSetOperations zSetOperations;
/**
* 操作ZSet,使用ZSetOperations,有序排列且无重复数据
* 对应写命令: ZADD
*/
@GetMapping("/zSetOperations")
public Object loadData06() {
log.info("ZSetOperations操作开始...");
// 1.增
zSetOperations.add("CityInfo:Hangzhou06", "杭州", 20);
zSetOperations.add("CityInfo:Hangzhou06", "苏州", 10);
zSetOperations.add("CityInfo:Hangzhou06", "上海", 30);
zSetOperations.add("CityInfo:Hangzhou06", "北京", 101);
zSetOperations.add("CityInfo:Hangzhou06", "宁波", 999);
// 2.1查(通过下标查值,从0开始取第一个值)
Set set = zSetOperations.range("CityInfo:Hangzhou06", 1, 4);
set.forEach((value) -> {
System.out.println("value=" + value);
});
// 2.2查(通过Score查值)
set = zSetOperations.rangeByScore("CityInfo:Hangzhou06", 29, 60);
set.forEach((value) -> {
System.out.println("value=" + value);
});
// 3.改
zSetOperations.add("CityInfo:Hangzhou06", "杭州", 99);
// 4.1取(取出Score最大的值,取出后队列中值会删除)
ZSetOperations.TypedTuple obj1 = zSetOperations.popMax("CityInfo:Hangzhou06");
System.out.println("取出最大值,value=" + obj1.getValue() + ",Score=" + obj1.getScore());
// 4.2取(取出Score最小的值,取出后队列中值会删除)
ZSetOperations.TypedTuple obj2 = zSetOperations.popMin("CityInfo:Hangzhou06");
System.out.println("取出最小值,value=" + obj2.getValue() + ",Score=" + obj2.getScore());
// 5.1删除指定值
zSetOperations.remove("CityInfo:Hangzhou06", "上海");
// 5.2按照Score分数大小删除
zSetOperations.removeRangeByScore("CityInfo:Hangzhou06", 1, 100);
// 5.3删(删除全部)
redisTemplate.delete("CityInfo:Hangzhou06");
// 6.设置超时
zSetOperations.add("CityInfo:Hangzhou06", "杭州", 21);
zSetOperations.add("CityInfo:Hangzhou06", "苏州", 11);
redisTemplate.boundValueOps("CityInfo:Hangzhou06").expire(5, TimeUnit.MINUTES);
redisTemplate.expire("CityInfo:Hangzhou06", 10, TimeUnit.MINUTES);
// 7.查询ZSet的元素个数
Long size =zSetOperations.size("CityInfo:Hangzhou06");
System.out.println("查询ZSet的元素个数,size="+size);
log.info("ZSetOperations操作结束...");
return "执行成功";
}
}
8.3 Test verification
Use Postman test.
Request RUL: http://127.0.0.1:18205/hub-205-redis/hub/example/load/zSetOperations
9. Visualization tool RedisDesktopManager
In the visualization tool RedisDesktopManager, you can query Redis related information.
When operating ZSetOperations, the name: CityInfo:Hangzhou06, separated by a colon, will be automatically converted to a folder in RedisDesktopManager. With multiple levels of colons, there are multiple folders.
TTL: 591, which is the cache expiration time, generally in seconds.
Above, thanks.
April 12, 2023