首页 > 编程语言 > 详细

19、SpringBoot 使用Redis作为缓存

时间:2021-06-21 15:36:10      阅读:6      评论:0      收藏:0      [点我收藏+]

1、添加redis的场景启动器依赖

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

2、编写application.yml配置

技术分享图片

 

 3、测试使用redisTemplate和StringRedisTemplate

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedisTemplate<Object, Object> myRedisTemplate;

    @Test
    void test() {
        //stringRedisTemplate.opsForValue().set("msg","hello,word");
        Employee empId = employeeService.getEmpId(1);
        myRedisTemplate.opsForValue().set("emp-01",empId);
    }

4、编写自定义的redisTemplate,用Json序列化保存数据到redis 的配置类

@Configuration
public class MyRedisConfig {

    @Bean
    public RedisTemplate<Object, Object> myRedisTemplate(RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer(Object.class);
        template.setDefaultSerializer(serializer);
        return template;
    }
}

6、如果将Java对象保存到redis中,需要将这个实体类实现序列化

public class Employee implements Serializable

 

19、SpringBoot 使用Redis作为缓存

原文:https://www.cnblogs.com/shunWcs/p/14912416.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!