由于blog各种垃圾评论太多,而且本人审核评论周期较长,所以懒得管理评论了,就把评论功能关闭,有问题可以直接qq骚扰我

SpringBoot与Redis7交互

JAVA 西门飞冰 2287℃

介绍

Spring Boot 内置了spring-boot-starter-data-redis这个模块用于简化Spring与Redis的 交互过程。

Spring-data-redis是spring大家族的一部分,提供了在spring应用中通过简单的配置访问 redis服务,对reids底层开发包(Jedis, JRedis, and RJC)进行了高度封装, RedisTemplate提供了redis各种操作、异常处理及序列化,支持发布订阅,并对spring 3.1 cache进行了实现。

环境说明:

spring boot:2.4.1

redis:7.0.5

开发过程

1、maven依赖配置

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>

额外引入commons-pool2是因为data-redis底层Redis连接池基于apache commons pool2开 发,不加入依赖会报ClassNotFoundException错误

注意:

  • Spring Boot 2后默认使用Lettuce作为访问redis的客户端
  • Lettuce是一个可伸缩线程安全的Redis客户端,它利用优秀netty NIO框架来高效 地管理连接池。

2、配置application.yml

starter-data-redis默认利用lettuce作为连接池组件,配置时除了配置Redis连接信息外,还 需要设置连接池

spring:
  redis:
    host: 172.16.247.3
    port: 6379
    password: 123456
    lettuce:
      pool:
        #最大允许连接数
        max-active: 100
        #最小空闲连接数,最少准备5个可用连接在连接池候着
        min-idle: 5
        #最大空闲连接数,空闲连接超过10个后自动释放
        max-idle: 10
        #当连接池到达上限后,最多等待30秒尝试获取连接,超时报错
        max-wait: 30000
    timeout: 2000

3、代码编写

利用RedisTemplate对象开发 spring-redis中使用了RedisTemplate来进行redis的操作,在Spring Boot IoC容器启动后 创建,在应用中可以直接注入使用

import com.fblinux.sbredis.SbredisApplication;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@SpringBootTest(classes = SbredisApplication.class)
public class RedisTemplateTestor {
    @Resource
    private RedisTemplate redisTemplate;

    @Test
    public void testString(){
        redisTemplate.opsForValue().set("name","fblinux");
        String name = (String) redisTemplate.opsForValue().get("name");
        System.out.println();
    }

    @Test
    public void testHash(){
        redisTemplate.opsForHash().put("website" , "name" , "fblinux");
        Map map = new HashMap<>();
        map.put("name", "张三");
        map.put("hiredate", "2022-05-06");
        redisTemplate.opsForHash().putAll("employee",map);
        Map employee = redisTemplate.opsForHash().entries("employee");
        System.out.println(employee);
    }

    @Test
    public void testBasic(){
        redisTemplate.expire("employee", 30, TimeUnit.MINUTES);
        redisTemplate.delete("employee");
    }

    @Test
    public void  testList(){
        redisTemplate.opsForList();
    }
    @Test
    public void testSet(){
        redisTemplate.opsForSet();
    }
    @Test
    public void testZset(){
        redisTemplate.opsForZSet();
    }
}

Spring Boot Redis序列化问题

默认情况下,Redis缓存和Redis模板配置为使用Java本地序列化。一般来说,我们强烈推荐任何其他消息格式(如JSON)。 因为Java本地序列化存在性能和安全性的问题。

Jackson对象序列化配置

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
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 RedisTemplateConfiguration {
    @Bean
    public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory factory){
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
        // 使用Jackson2JsonRedisSerialize 替换默认序列化
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        //忽略任何值为null的属性
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        // 设置key和value的序列化规则
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        // 设置hashKey和hashValue的序列化规则
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        //afterPropertiesSet和init-method之间的执行顺序是afterPropertiesSet 先执行,init-method 后执行。
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

通过String类型测试序列化

    @Test
    public void testString(){
        Map map = new HashMap();
        map.put("a", "b");
        redisTemplate.opsForValue().set("age" , map);
        Map age = (Map)redisTemplate.opsForValue().get("age");
        System.out.println(age);
    }

客户端验证已经序列化成了json格式

image-20221016161237004

Spring Boot访问redis哨兵和集群

访问哨兵和redis cluster集群,只需要注释掉单机版本的host和port配置,打开哨兵或集群的注释,并配置对应IP信息即可。

spring:
  redis:
#    host: 172.16.247.3
#    port: 6379
    password: 123456
    #设置默认访问的数据库
    database: 1
    # 设置超时时间
    timeout: 2000
    lettuce:
      pool:
        #最大允许连接数
        max-active: 100
        #最小空闲连接数,最少准备5个可用连接在连接池候着
        min-idle: 5
        #最大空闲连接数,空闲连接超过10个后自动释放
        max-idle: 10
        #当连接池到达上限后,最多等待30秒尝试获取连接,超时报错
        max-wait: 30000
    #redis哨兵配置
    sentinel:
      master:
      nodes:
        - 172.16.247.3:26379,172.16.247.4:26379,172.16.247.4:26379
    # redis集群配置
#    cluster:
#      max-redirects:
#      nodes:
#        - 172.16.247.3:6379,172.16.247.4:6379,172.16.247.5:6379,172.16.247.6:6379,172.16.247.7:6379,172.16.247.8:6379

转载请注明:西门飞冰的博客 » SpringBoot与Redis7交互

喜欢 (0)or分享 (0)