Redis 整合Redis. Templace
创建时间:2025-10-26 18:45
长度:2644
浏览:0
评论:0
在我们使用Jedis的时候,如果我们想要完成一些Redis的操作,对应的命令其实就是对应的方法,比如Set在Jedis中也就是set(方法,虽然很好上手,但是这会导致我们的代码比较臃肿,而既然SpringData出手整合了,它必然会按照一定的规律做进一步的封
装,具体如下:
redisTemplate.ops..方法囊括了几乎所有的Redis不同数据类型的命令操作
• 操作String类型数据:redisTemplate.opsForValue()
• 操作List数据类型:redisTemplate.opsForList()
• 操作Hash数据类型:redisTemplate.opsForHash()
• tRIFSet#*#: redisTemplate.opsForSet()
• 操作ZSet数据类型:redisTemplate.opsForZSet()
• 以上这些方法返回的都是...Operations类型,比如
• ValueOperations其中包括的就是String类型的所有操作:Set、Get等
注意:RedisTemplate中还封装着一些通用的或者特殊的操作
要使用Redis Templace
就要用到一些依赖
如果是新项目

依赖(如果勾选了Spring Data redis,就不用管)
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>在项目中的application.yml配置redis
spring:
  data:
    redis:
      database: 1
      host: localhost
      port: 6379
这样就可以完成使用了
package org.huangcy.redisdemo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
@SpringBootTest
class RedisDemoApplicationTests {
    @Autowired
    private RedisTemplate redisTemplate;
    @Test
    void contextLoads() {
        redisTemplate.opsForValue().set("aa:name", "huangcy");
        System.out.println(redisTemplate.opsForValue().get("name"));
    }
}
自定义配置redisTemplace (解决key乱码的问题,原来key是用Object)
package org.huangcy.redisdemo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        // 为了开发方便,key直接设置为String 类型
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 设置连接工厂
        template.setConnectionFactory(redisConnectionFactory);
        // 序列化配置,通过JSON 解析任意对象
        GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        // 设置key和value的序列化方式
        template.setKeySerializer(RedisSerializer.string());
        template.setHashValueSerializer(RedisSerializer.string());
        template.setValueSerializer(genericJackson2JsonRedisSerializer);
        template.setHashValueSerializer(genericJackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}