SpringBoot如何集成redis,实现数据缓存?

SpringBoot 集成 Redis

前提是 aliyun 服务器开着

1.导入 redis jar包

pom.xml

<!-- redis非关系型数据库 -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2.配置连接 redis

spring:
  #配置连接redis
  redis:
    host: 121.196.238.100
    port: 6379
    password: 111
    database: 0
    pool:
      max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
      max-wait: -1ms # 连接池最大阻塞等待时间(使用负值表示没有限制)
      max-idle: 8 # 连接池中的最大空闲连接
      min-idle: 0 # 连接池中的最小空闲连接
      timeout: 5000ms # 连接超时时间(毫秒)

注意连接时要在 aliyun服务器对6379端口放行:加入安全组

在这里插入图片描述

3.测试是否连接成功

1)注入redistemplate时测试

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5k37hsj3-1648022242074)(C:\Users\16431\AppData\Roaming\Typora\typora-user-images\image-20220322144319869.png)]

2)连接运行测试

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wSNl1Uw2-1648022242075)(C:\Users\16431\AppData\Roaming\Typora\typora-user-images\image-20220322145702382.png)]

package com.ffyc.ssmback;

import com.mysql.cj.util.TimeUtil;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.concurrent.TimeUnit;

@SpringBootTest
class SsmbackApplicationTests {

   @Autowired
   RedisTemplate redisTemplate;

   @Test
   void contextLoads() {

      ValueOperations<String,String> valueOperations = redisTemplate.opsForValue();
         valueOperations.set("name", "jim",20, TimeUnit.SECONDS);
            String s = valueOperations.get("name");
         System.out.println(s);
         System.out.println(redisTemplate.hasKey("name"));  //判断是否存在键
/*       redisTemplate.delete("name");
         System.out.println(redisTemplate.hasKey("name"));*/
   }

}

3)键值 序列化

配置Redis.conf文件

package com.ffyc.ssmback.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    /**
     * 序列化键,值
     * @param connectionFactory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
        StringRedisSerializer redisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(redisSerializer);//键 --> 字符串
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);//值序列化为json格式
        /*redisTemplate.setHashKeySerializer();
        redisTemplate.setHashValueSerializer();*/
        return redisTemplate;
    }
}

序列化测试:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7AsZbxbU-1648022242076)(C:\Users\16431\AppData\Roaming\Typora\typora-user-images\image-20220323101753180.png)]

SsmbackApplicationTests.java

 @Test
public void test(){
       //缓存一个对象  User对象  序列化
       ValueOperations<String,Object> valueOperations = redisTemplate.opsForValue();
   /*StringRedisSerializer redisSerializer = new StringRedisSerializer();
   Jackson2JsonRedisSerializer JsonRedisSerializer = new Jackson2JsonRedisSerializer(User.class);
   //用String类型也可以缓存对象,集合 要将对象序列化为json格式的字符串
   redisTemplate.setKeySerializer(redisSerializer); //对key键序列化为String类型
   redisTemplate.setValueSerializer(JsonRedisSerializer);  //对Value值序列化为json类型*/
   User user = new User();
       valueOperations.set("user", user,100,TimeUnit.SECONDS);

}

4.缓存使用

  • 在service层做
  • 缓存一般在前台很少变动的数据,使用量大的数据

例如:前台新闻类型的查询

第一次查询,在缓存中去找,如果缓存中没有,就去数据库中查找,并把查到的数据存放在缓存中一段时间,方便下次去缓存中找。

//查询新闻类型列表
public List<NewsType> findTypes() {
    /*
        第一次查询,上缓存里面查
            如果缓存里面没有,就去数据库中查,并把查到的list放到缓存中10s/10min/10h/1天...
     */
    List<NewsType> list = ( List<NewsType>)redisTemplate.opsForValue().get("newstypes");
    if(list==null){
        list = frontDao.findTypes();
        //把数据放到缓存中
        redisTemplate.opsForValue().set("newstypes", list,10, TimeUnit.SECONDS);
        //redisTemplate.opsForValue().set("newstypes", list,1,TimeUnit.DAYS); //缓存一天,这一天之内都从存中拿数据就行

    }
    return list;
}

需要被 Redis 缓存的类,必须实现序列化接口

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宋大米Pro

感谢小主大赏,留言可进互助群~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值