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

springboot整合redis和cache

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

springboot整合redis和cache

第一步:首先加入两个依赖

        
			org.springframework.boot
			spring-boot-starter-data-redis
		
		
			org.springframework.boot
			spring-boot-starter-cache
		

第二步:在application配置文件中 对redis进行配置

spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=

第三步:添加一个配置文件

import org.springframework.cache.annotation.EnableCaching;
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.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import java.time.Duration;


@Configuration
@EnableCaching
public class CachingConfig {

    @Bean
    public RedisCacheManager redisCacheManager(RedisConnectionFactory connectionFactory){
        RedisCacheWriter redisCacheWriter = RedisCacheWriter
                .lockingRedisCacheWriter(connectionFactory);
        RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        cacheConfiguration = cacheConfiguration.entryTtl(Duration.ofSeconds(30));

        RedisCacheManager redisCacheManager = new RedisCacheManager(redisCacheWriter,
                cacheConfiguration);
        return redisCacheManager;
    }
}

第四步:在启动类上加注解

@EnableCaching

代表开启缓存

第五步:在需要缓存的方法上加注解

@Cacheable(value = "listCategoryForCustomer")    value就是存储时的key值

第六步:测试

注意:如果启动的时候报异常,很大可能是因为你的实体类没有序列化,在实体类上加

implements Serializabl  再重新运行

我们第一次运行的时候需要花很长一段时间,如下图

 然后进行第二次访问时,速度就大大提升了

此时也可以看到我们的redis中已经有key值存在了

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

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

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