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

利用redis+SpringCache实现缓存功能

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

利用redis+SpringCache实现缓存功能

写的很简单,为了实现功能。如果有错误,请大佬指出。

1.添加依赖
    
      org.springframework.boot
      spring-boot-starter-data-redis
    
    
      org.springframework.boot
      spring-boot-starter-cache
    
2.配置redis信息
spring:
	redis:
		host: localhost #地址
		post: 6379 #端口
		password: xxxx #密码,没有可以不用写
		database: 0 #使用redis中的哪个库
		timeout: 3000 #超时时间,单位是毫秒
3.在启动类添加@EnableCaching注解
@EnableCaching
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
4.在方法上添加@Cacheable注解,value代表存储时的key值。
    @Override
    @Cacheable(value = "XX")
    public List XX(Integer Id) {
        ...
    }
5.配置一个配置类CacheConfig
@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    public RedisCacheManager redisCacheManager(RedisConnectionFactory connectionFactory) {
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.lockingRedisCacheWriter(connectionFactory);
        RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        cacheConfiguration = cacheConfiguration.entryTtl(Duration.ofSeconds(60));
        RedisCacheManager redisCacheManager = new RedisCacheManager(redisCacheWriter,cacheConfiguration);
        return redisCacheManager;
    }
}

以上配置完就可以实现缓存功能。

注:如果碰到异常:Cannot serialize,说明实体类没有被序列化,将实体类继承Serializable。

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

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

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