1、添加依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2、配置redis

通过 spring.redis.xxx 来配置 redis 的信息

spring.redis.host=127.0.0.1
spring.redis.port=6379

#常见的配置
spring.redis.host=redis所在的ip地址
spring.redis.port=端口,默认为6379,如果默认为6379,则不用配置中
spring.redis.password=登录密码,如果没有设置,则不用配置

3、测试

在进行测试前,需要知道操作 redis 需要一个类似 jdbcTemplate 的东西,我们可通过在 RedisAutoConfiguration 类中可以发现

@AutoConfiguration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {

	@Bean
	@ConditionalOnMissingBean(name = "redisTemplate")
	@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
	public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
		RedisTemplate<Object, Object> template = new RedisTemplate<>();
		template.setConnectionFactory(redisConnectionFactory);
		return template;
	}

	@Bean
	@ConditionalOnMissingBean
	@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
	public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
		return new StringRedisTemplate(redisConnectionFactory);
	}

}

其中配置两个 bean 用于操作 redis。其中 RedisTemplate操作的 key-value 是object类型。

而 StringRedisTemplate 则是操作 key-value 都是 String 类型,证明如下:其继承了 RedisTemplate

public class StringRedisTemplate extends RedisTemplate<String, String> {}

两者区别是第一个没有确定类型,第二个已经确定了key的类型为string,所以当知道key的类型为string时,直接使用第二个。
对于第一个而言,会将对象序列化后存入(因为redis存入的是字符串,不会将对象传入)

ok,接下来开始测试

创建实体类,且实例化

public class User implements Serializable {
    private Long uid;
    private String uName;
    //get、set、tostring
}

因为 redis 中存入的是序列化后的对象

测试

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Test
    void contextLoads() {
        //字符操作
        ValueOperations ops = redisTemplate.opsForValue();
        User user = new User();
        user.setUid(4L);
        user.setuName("wa");
        //设置 key-value
        ops.set("u", user);
        //通过键获取value
        User u = (User) ops.get("u");
        System.out.println("u = " + u);
    }

    @Test
    void test() throws JsonProcessingException {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        User user = new User();
        user.setUid(2L);
        user.setuName("麻子");
        //获取ObjectMapper对象,用于序列化
        ObjectMapper mapper = new ObjectMapper();
        //将对象序列化
        String s = mapper.writeValueAsString(user);
        //redis存入数据
        ops.set("u1", s);
        //获取数据
        String u1 = ops.get("u1");
        //反序列化
        User user1 = mapper.readValue(u1, User.class);
        System.out.println("user1 = " + user1);
    }
posted on 2023-06-16 11:33  xashould  阅读(18)  评论(0编辑  收藏  举报