• springboot项目如何把数据加入缓存中(用@Cacheable注解)


    PS:如有问题,评论留言。

    先引入依赖

    <dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-cache</artifactId>

    </dependency>

    激活启动类注解@EnableCaching

    实现类相应方法上加上这个注解

    @Service

    public class ImsSysClientServiceImpl implements ImsSysClientService {
    @Resource
    ImsSysClientMapper imsSysClientMapper;


    @Cacheable(value = "client", key = "#id", unless = "#result == null")
    public ImsSysClient selectByPrimaryKey(Integer id) {
    return imsSysClientMapper.selectByPrimaryKey(id);
    }
    controller层测试代码
    public void test(){
    System.out.println("test");
    ImsSysClient client1=imsSysClientService.selectByPrimaryKey(1);
    System.out.println(client1);
    ImsSysClient client2=imsSysClientService.selectByPrimaryKey(1);
    System.out.println(client2);


    }
    默认用redis缓存

    如果不想用redis缓存,只是把它放内存中。(在serviceImpl里面加入下面这个管理器)
     @Bean
        public CacheManager cacheManager() {
            SimpleCacheManager cacheManager = new SimpleCacheManager();
            cacheManager.setCaches(Arrays.asList(new ConcurrentMapCache("client"),new ConcurrentMapCache("clientId"),new ConcurrentMapCache("jwtinfo")));
            cacheManager.afterPropertiesSet();
            return cacheManager;
        }
    }
    
    如果配了多个不同名字的缓存注解,在红线部分把名字配上去。不过这个管理器不能放在单独的文件中,否则又会使用redis缓存。(我也不知道为什么)


  • 相关阅读:
    Java基础总结--面向对象1
    Java基础总结--数组
    Java基础总结--方法(函数)
    Java基础总结--流程控制
    Java基础总结--变量、运算符总结
    Java基础总结--Java编程环境变量配置
    OpenWrt源码结构
    OpenWRT介绍
    内存管理
    makefie中的几种用法
  • 原文地址:https://www.cnblogs.com/yxj808/p/13395607.html
Copyright © 2020-2023  润新知