Spring Boot 2.1.0.RELEASE 使用 Redis 缓存数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qmqm011/article/details/88183475

Spring对缓存的支持,可以参考这篇文章

本例基于Spring Boot 2.1.0.RELEASE 整合 Redis,在此基础上增加使用Redis缓存数据。

修改RedisConfig配置类,增加CacheManager的配置,修改后的RedisConfig如下:

package com.wuychn;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);
        GenericFastJsonRedisSerializer genericFastJsonRedisSerializer = new GenericFastJsonRedisSerializer();
        redisTemplate.setValueSerializer(genericFastJsonRedisSerializer);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    // 缓存管理器,与SpringBoot 1.x有很大区别
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair
                .fromSerializer(new GenericFastJsonRedisSerializer());
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofHours(1)) // 指定过期时间
                .serializeValuesWith(pair); // value的序列化
        return RedisCacheManager
                .builder(RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory))
                .cacheDefaults(redisCacheConfiguration)
                .build();
    }

}

修改启动类,增加@EnableCaching注解,并新增一个testCache()方法用作测试:

package com.wuychn;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
@EnableCaching
public class SpringBootRedisApplication {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    public static void main(String[] args) {
        SpringApplication.run(SpringBootRedisApplication.class, args);
    }

    @GetMapping("/set")
    public String set(String value) {
        redisTemplate.opsForValue().set("hello", value);
        return "success";
    }

    @GetMapping("/get")
    public String get() {
        Object value = redisTemplate.opsForValue().get("hello");
        return value.toString();
    }

    @GetMapping("/testCache")
    @Cacheable(value = "cacheName")
    public String testCache() {
        System.out.println("查询数据库...");
        return "data";
    }

}

启动项目,在浏览器中访问http://localhost:8080/testCache,可以看到控制台打印出了如下语句:

之后刷新页面,可以看到控制台没有打印出“查询数据库”,说明缓存生效了。

查看Redis:

可以看到数据的确被缓存进去了,并且过期时间是1个小时。

如果在Redis中执行flushdb命令(清空数据),再次刷新页面,可以看到控制台又会打印出“查询数据库”。

 

猜你喜欢

转载自blog.csdn.net/qmqm011/article/details/88183475