1. 程式人生 > 其它 >19、SpringBoot 使用Redis作為快取

19、SpringBoot 使用Redis作為快取

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