【四】Redis从入门到放弃---RedisTemplate操作Redis
Spring对Redis的支持一般是实用Jedis操作的,在上一篇文章中也有详细介绍了。那么SpringBoot对Redis的支持则是使用 了自动配置RedisAutoConfiguration中的RedisTemplate与StringRedisTemplate,RedisTemplate和StringRedisTemplate的区别:StringRedisTemplate继承了RedisTemplate;RedisTemplate是一个泛型类,而StringRedisTemplate则不是;RedisTemplate可以对任何类型的key-value键值对操作StringRedisTemplate的key-value键值都只能是String类型;两者序列化/反序列化不同。
我们接下来就介绍下RedisTemplate是如何操作Redis的吧:
(1)添加依赖
<!-- redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- spring2.X集成redis所需common-pool2--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.6.0</version> </dependency>
(2)使用配置文件配置Redis
application.properties
#Redis服务器地址 spring.redis.host=47.106.195.84 #Redis服务器连接端口 spring.redis.port=6379 #有密码的设置下密码 spring.redis.password=***** #Redis数据库索引(默认为0) spring.redis.database= 15 #连接超时时间(毫秒) spring.redis.timeout=1000 #连接池最大连接数(使用负值表示没有限制) spring.redis.lettuce.pool.max-active=20 #最大阻塞等待时间(负数表示没限制) spring.redis.lettuce.pool.max-wait=-1 #连接池中的最大空闲连接 spring.redis.lettuce.pool.max-idle=5 #连接池中的最小空闲连接 spring.redis.lettuce.pool.min-idle=0
或者application.yml
spring: redis: port: 6379 database: 15 host: 47.106.195.84 password: jedis: pool: max-active: 8 max-wait: -1ms max-idle: 8 min-idle: 0 timeout: 5000ms
(3)添加redis配置类
@EnableCaching @Configuration @EnableTransactionManagement//开启事务管理 public class RedisConfig extends CachingConfigurerSupport { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); RedisSerializer<String> redisSerializer = new StringRedisSerializer(); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); //指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常 om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); // 配置连接工厂 template.setConnectionFactory(factory); //key序列化方式 template.setKeySerializer(redisSerializer); //value序列化 template.setValueSerializer(jackson2JsonRedisSerializer); //设置hash key 和value序列化模式 template.setHashValueSerializer(jackson2JsonRedisSerializer); //打开事务支持 template.setEnableTransactionSupport(true); return template; } @Bean public CacheManager cacheManager(RedisConnectionFactory factory) { RedisSerializer<String> redisSerializer = new StringRedisSerializer(); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); //解决查询缓存转换异常的问题 ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); // 配置序列化(解决乱码的问题),过期时间600秒 RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofSeconds(600)) .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer)) .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)) .disableCachingNullValues(); RedisCacheManager cacheManager = RedisCacheManager.builder(factory) .cacheDefaults(config) .build(); return cacheManager; } }
(4)添加redis测试类
/** * RedisTemplate 对五种数据结构分别定义了操作 * * 操作字符串:redisTemplate.opsForValue(); * * 操作list:redisTemplate.opsForList(); * * 操作set:redisTemplate.opsForSet(); * * 操作hash:redisTemplate.opsForHash(); * * 操作有序set:redisTemplate.opsForZSet(); * */ @RestController @RequestMapping("/redisTest") public class TestRedisController { @Autowired private RedisTemplate redisTemplate; /** * 对String类型操作 * * @return */ @GetMapping("/testString") public String testString() { //设置值到redis redisTemplate.opsForValue().set("string01", "lucy"); redisTemplate.opsForValue().set("string02", "lucy1", 60);//并设置有效时间的 //从redis获取值 String name = (String) redisTemplate.opsForValue().get("string01"); return name; } /** * 对List类型操作 * * @return */ @GetMapping("testList") public String testList() { //从左边设置值给list01 redisTemplate.opsForList().leftPush("list01", "value01");//单个 redisTemplate.opsForList().leftPushAll("list01", "value02", "value03", "value04");//多个 ArrayList<String> list = new ArrayList<>(); list.add("add01"); list.add("add02"); list.add("add03"); list.add("add04"); redisTemplate.opsForList().leftPushAll("list01", list);//集合方式 //获取某个key的长度 System.out.println(redisTemplate.opsForList().size("list01")); System.out.println(redisTemplate.opsForList().range("list01", 0, -1)); return "ok"; } /** * 对Hash类型操作 * * @return */ @GetMapping("testHash") public String testHash() { redisTemplate.opsForHash().put("hash01", "hkey01","value01");//单个 Map<String,String> map = new HashMap<>(); map.put("addAll01","v1"); map.put("addAll02","v2"); map.put("addAll03","v3"); map.put("addAll04","v4"); redisTemplate.opsForHash().putAll("hash01", map);//集合方式 //获取某个key的长度 System.out.println(redisTemplate.opsForHash().keys("hash01")); //删除 redisTemplate.opsForHash().delete("hash01", "addAll01"); //判断是否存在 System.out.println(redisTemplate.opsForHash().hasKey("hash01", "addAll01")); //获取某个key的值 System.out.println(redisTemplate.opsForHash().values("hash01")); return "ok"; } }