springboot---redis缓存的使用

本文详细介绍了如何在SpringBoot项目中配置并使用Redis缓存。包括下载安装Redis、配置application.properties文件、设置序列化方式及使用示例。通过具体代码展示了如何在方法中读取和写入缓存数据。

1、下载redis安装包,解压到电脑

2、启动redis

3、springboot  application.properties中配置redis缓存

spring.redis.host=127.0.0.1  //redis的地址
spring.redis.port=6379  //端口
//密码,默认为空
spring.redis.password=
# Redis服务器连接密码(默认为空)
spring.redis.password=

# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8

# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1

# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8

# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0

# 连接超时时间(毫秒)
spring.redis.timeout=0
 

 使用:

1、

RedisSerializer redisSerializer = new StringRedisSerializer();
@Autowired
private RedisTemplate<Object, Object> redisTemplate;

2、方法体中使用:
 @Override
    public Page<Product> getProductListByPage(int page, String productType, int count, Sort sort) {
        redisTemplate.setKeySerializer(redisSerializer);  //序列化
        Page<Product> product= (Page<Product>) redisTemplate.opsForValue().get("getProduct");  //从缓存中获取数据
        if (product==null){
            synchronized (new Object()){
                if (product==null){
                    Specification<Product> specification=pageableTool.specifucation(productType);
                    Pageable pageable = PageRequest.of(page, count, sort);
                    product= productRepository.findAll(specification, pageable);
                    redisTemplate.opsForValue().set("getProduct",product);  //将数据写入redis缓存中
                    return product;
                }
            }
        }
        return product;
    }

  3、实体类必须实现 Serializable (redis包自带的)

  

 




转载于:https://www.cnblogs.com/qq1141100952com/p/9606914.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值