Spring cache 使用 redis 缓存


Reids是 键值对 缓存数据库

Redis官网

redis官网不支持windows版本

windows版本下载在这里

demo

pom.xml

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

applciation.yml

spring:
  cache:
#    cache-names 没有生效
#    cache-names:
#      - cache1
#      - cache2
#    type: redis
    redis:
#      缓存生存时间5s 过期自动消除
      time-to-live: 5000
  redis:
#    redis ip
    host: 127.0.0.1
#    redis 密码
    password: jsong
#    端口号
    port: 6379
server:
  port: 8081

redis缓存的配置也可以通过配置bean的形式实现

RedisConfig.java

bean中还配置了redis key value序列化的配置,防止乱码
这篇博客记录了学习过程中的乱码问题
RedisTemplate bean 可以注释掉, 是用来set get redis缓存的,也做了序列化处理

	为什么需要序列化呢
	正常我们在使用oracle,mysql存储的时候,同样需要序列化
	只不过这部分工作jdbc帮我们做了,我们不需要在做了
package com.jsong.wiki.redis.config;

import org.springframework.cache.CacheManager;
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.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

import static java.util.Collections.singletonMap;


@Configuration
public class RedisConfig {


    @Bean("myRedisTemplate")
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate redisTemplate = new RedisTemplate();

        redisTemplate.setConnectionFactory(redisConnectionFactory);

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // 序列化key 否则乱码
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);

        GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        // 序列化value 否则乱码
        redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer);
        return redisTemplate;
    }

    @Bean
    public CacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory)
                .cacheDefaults(defaultCacheConfig())
                .withInitialCacheConfigurations(singletonMap("predefined", defaultCacheConfig().disableCachingNullValues()))
                .transactionAware()
                .build();

        return cacheManager;
    }
// redis配置
    private RedisCacheConfiguration defaultCacheConfig() {
        //  TTL  Time To Live
        /*前缀
         * 过期时间 10s == yml  spring.cache.redis.time-to-live
         * key序列化
         * value序列化
         * */
        RedisCacheConfiguration redisCacheConfiguration =
                RedisCacheConfiguration.defaultCacheConfig()
                        .prefixKeysWith("redis:")
                        .entryTtl(Duration.ofSeconds(10))
                        .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                        .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));

        return redisCacheConfiguration;
    }
}

RedisService.java

这里用到的缓存注解

  • @EnableCaching
    开启缓存

  • @CacheConfig(cacheManager = “redisCacheManager”)
    指定缓存的manager

  • @Cacheable(value = “cache1”,key = “#root.caches[0].name”)
    设定缓存的key和value

Spring 缓存介绍,注解请看这里

package com.jsong.wiki.redis.service;

import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.stereotype.Component;

@EnableCaching
@CacheConfig(cacheManager = "redisCacheManager")
@Component
public class RedisService {

    @Cacheable(value = "cache1",key = "#root.caches[0].name")
    public String getCache1() {
        return "cache1Value";
    }

    @Cacheable(value = "cache2",key = "#root.caches[0].name")
    public String getCache2() {
        return "cache2Value";
    }
}

RedisController.java

package com.jsong.wiki.redis.controller;

import com.jsong.wiki.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
public class RedisController {
    @Autowired
    RedisService redisService;

    @RequestMapping("/cache1")
    public String getCache1() {
        redisService.getCache2();
        return redisService.getCache1();
    }
}

访问测试

http://localhost:8081/test/cache1

可以看到redis中已经有我们的缓存数据了
在这里插入图片描述

由于我们设置了过期时间,过期后redis就会把缓存清除

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值