Spring Boot Redis 数据缓存

前言

之前都是在Spring MVC中使用Redis,这里记录在Spring Boot中使用Redis作为数据缓存的过程。参考Spring Boot集成Spring Data Jpa,搭建项目。

启动Redis

本次是在Docker中部署Redis,从https://hub.docker.com/中直接pull官方的redis镜像,启动redis。

这里写图片描述

使用RedisDesktopManager测试一下。。。

这里写图片描述

连接成功了。接下来看看Spring Boot中怎么使用Redis。

集成

POM文件

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

Redis配置

application.properties

# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=0  
# Redis服务器地址
spring.redis.host=192.168.99.100
# Redis服务器连接端口
spring.redis.port=6379  
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8  
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1  
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8  
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0  
# 连接超时时间(毫秒)
spring.redis.timeout=0  

RedisCacheConfig类

@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {
    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, String> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

    @SuppressWarnings("rawtypes")
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
        //设置缓存过期时间,默认是0l
        rcm.setDefaultExpiration(60);//秒
        return rcm;
    }

}

使用

    @RequestMapping(value = "/search", method = RequestMethod.POST)
    @Cacheable(value = "search")
    public ModelMap search() {
        List<User> userList = userService.selectAll();
        LOGGER.info("search....");
        return result(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, userList);
    }

测试

  1. PostMan发起请求

这里写图片描述
2. 后台接受请求

这里写图片描述

这里写图片描述
3. 返回值

这里写图片描述
4. 缓存

使用RedisDesktopManager 查看缓存的结果。

这里写图片描述

下次请求,会直接从redis返回结果。不会再请求数据库,接口响应的时间大大缩短。

这里写图片描述

参考

Cache Abstraction
Caching Data with Spring

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值