Spring cache cache using redis


Reids is key to the cache database

Redis official website

redis official website does not support the version of windows

windows version download here

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 cache configurations can also be implemented by configuring the form bean

RedisConfig.java

the bean is also equipped with redis key value serialized configuration, to prevent distortion of
this blog records the learning process the garbage problem
RedisTemplate bean can comment, is used to set get redis cache, also made a series of treatment

	为什么需要序列化呢
	正常我们在使用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

Here used caching comment

  • @EnableCaching
    open the cache

  • @CacheConfig (cacheManager = "redisCacheManager")
    specify the cache manager

  • @Cacheable (value = "cache1", key = "# root.caches [0] .name")
    is set and the cache key value

Spring cache descriptions, look at this comment

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();
    }
}

Access tests

http://localhost:8081/test/cache1

Redis can see we already have a data cache
Here Insert Picture Description

Since we set an expiration time, after the expiration redis will clear the cache

Here Insert Picture Description

Published 83 original articles · won praise 21 · views 50000 +

Guess you like

Origin blog.csdn.net/JsongNeu/article/details/103705013