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就会把缓存清除

在这里插入图片描述

发布了83 篇原创文章 · 获赞 21 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/JsongNeu/article/details/103705013