栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot缓存 集成Redis缓存

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot缓存 集成Redis缓存

依赖

缓存依赖

 
 
     org.springframework.boot
     spring-boot-starter-cache
 
配置类
package chang.redis.config;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.cache.interceptor.SimpleKeyGenerator;
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 java.util.HashMap;
import java.util.Map;


@EnableCaching
@Configuration
public class RedisCachingConfig {

    
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        redisCacheConfiguration = redisCacheConfiguration
                // 设置key采用String的序列化方式
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(StringRedisSerializer.UTF_8))
                //设置value序列化方式采用jackson方式序列化
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(serializer()))
                //当value为null时不进行缓存
                .disableCachingNullValues()
                // 配置缓存空间名称的前缀
                .prefixCacheNameWith("demo:")
                //全局配置缓存过期时间【可以不配置】
                .entryTtl(Duration.ofMinutes(30L));
        //专门指定某些缓存空间的配置,如果过期时间【主要这里的key为缓存空间名称】
        Map map = new HashMap<>();

//        Set> entries = ttlParams.entrySet();
//        for (Map.Entry entry : entries) {
//            //指定特定缓存空间对应的过期时间
//            map.put("user", redisCacheConfiguration.entryTtl(Duration.ofSeconds(40)));
//            map.put(entry.getKey(), redisCacheConfiguration.entryTtl(Duration.ofSeconds(entry.getValue())));
//        }

        return RedisCacheManager
                .builder(redisConnectionFactory)
                // 默认配置
                .cacheDefaults(redisCacheConfiguration)
                // 某些缓存空间的特定配置
                .withInitialCacheConfigurations(map)
                .build();
    }


    
    @Bean
    public KeyGenerator keyGenerator() {
        
        return (target, method, params) -> {
            //获取代理对象的最终目标对象
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getSimpleName()).append(":");
            sb.append(method.getName()).append(":");
            //调用SimpleKey的key生成器
            Object key = SimpleKeyGenerator.generateKey(params);
            return sb.append(key);
        };
    }


    
    public GenericJackson2JsonRedisSerializer serializer() {
        return new GenericJackson2JsonRedisSerializer();
    }

}
使用

具体怎么使用可以自行百度
例如:

package chang.web.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/cache")
public class CacheRedisController {

    private static final Logger logger= LoggerFactory.getLogger(CacheRedisController.class);

    @GetMapping("/t1")
    public String t1(){
        logger.info("执行Controller。");
        return cacheTest("a");
    }

    @Cacheable(cacheNames = "hello")
    public String cacheTest(String user_id){
        logger.info("缓存执行了。");
        return "缓存执行了。";
    }

}

注意,坑

其实上面的代码缓存是没有生效的,原理和事务失效一样,没有被AOP代理,事务是无法生效的

正确演示
package chang.web.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.AopContext;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/cache")
public class CacheRedisController {

    private static final Logger logger= LoggerFactory.getLogger(CacheRedisController.class);

    @GetMapping("/t1")
    public String t1(){
        logger.info("执行Controller。");

        // AOP 代理
        CacheRedisController cacheRedisController = (CacheRedisController)AopContext.currentProxy();

        return cacheRedisController.cacheTest("a");
    }

    @Cacheable(cacheNames = "hello")
    public String cacheTest(String user_id){
        logger.info("缓存执行了。");
        return "缓存执行了。";
    }

}

不过这么写的话,需要引入AOP依赖,在启动类上加注解

或者你可以直接使用自动注入去使用方法就行了

// 注解
@SpringBootApplication
@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)
public class SpringbootReadApplication {

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

 
 
     org.springframework.boot
     spring-boot-starter-aop
 
Redis 存储效果

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/936307.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号