SpringBoot集成Redis Cluster集群(附带Linux部署Redis Cluster高可用集群)

23 篇文章 0 订阅

一、前言

这里会使用到spring-boot-starter-data-redis包,spring boot 2的spring-boot-starter-data-redis中,默认使用的是lettuce作为redis客户端,也推荐使用lettuce,Redis使用哨兵集群,这里会通过lettuce连接到哨兵获取对应Redis节点地址从而操作Redis。

Linux部署Redis Cluster高可用集群:https://blog.csdn.net/weixin_44606481/article/details/134052367

二、集成配置

工程结构
在这里插入图片描述

2.1、POM

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.12.RELEASE</version>
    </parent>
    
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <!--springboot中的redis依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- lettuce pool 缓存连接池-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>
        <!-- 使用jackson作为redis数据序列化 -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.11.4</version>
        </dependency>
		<!-- SpringBoot测试包 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

2.2、添加配置文件application.yml

因为我们用的spring-boot-starter-data-redis包会自动配置redis连接,在配置文件中添加对应配置即可

spring:
  #redis配置信息
  redis:
    ## Redis数据库索引(默认为0)
    database: 0
    ## Redis服务器连接密码(默认为空)
    password: 123456
    ## 连接超时时间(毫秒)
    timeout: 5000
    ## 集群配置
    cluster:
      ### 集群中所有节点
      nodes:
        - 172.16.8.186:7001
        - 172.16.8.186:7002
        - 172.16.8.186:7003
        - 172.16.8.186:7004
        - 172.16.8.186:7005
        - 172.16.8.186:7006
      ### 最大重定向数,最好为集群节点数,比如第一台挂了,连第二台,第二台挂了连第三台,这个是重新连接的最大数量
      max-redirects: 6
    lettuce:
      pool:
        ## 连接池最大连接数(使用负值表示没有限制)
        max-active: 8
        ## 连接池最大阻塞等待时间(使用负值表示没有限制)
        max-wait: -1
        ## 连接池中的最大空闲连接
        max-idle: 8
        ## 连接池中的最小空闲连接
        min-idle: 1
      ## 集群配置
      cluster:
        refresh:
          # 支持集群拓扑动态感应刷新,自适应拓扑刷新是否使用所有可用的更新,默认false关闭,类似nacos定时刷新服务列表
          adaptive: true
          # 定时刷新时间 毫秒
          period: 2000

# 打印lettuce debug日志,方便查看读写分离效果
logging:
  pattern:
    console: '%date{yyyy-MM-dd HH:mm:ss.SSS} | %highlight(%5level) [%green(%16.16thread)] %clr(%-50.50logger{49}){cyan} %4line -| %highlight(%msg%n)'
  level:
    root: info
    io.lettuce.core: debug
    org.springframework.data.redis: debug

2.3、编写配置文件

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.lettuce.core.ReadFrom;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.HashSet;

@Configuration
public class RedisConfig{
    /**
     * retemplate相关配置,配置自定义序列化规则为jackson
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(factory);
        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);
        // 值采用json序列化
        template.setValueSerializer(jacksonSeial);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();
        return template;
    }
}

2.4、编写启动类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class LettuceApplication {
    public static void main(String[] args) {
        SpringApplication.run(LettuceApplication.class);
    }
}

2.5、编写测试类测试是否连接成功

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(classes =  LettuceApplication.class)
public class LettuceTest {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Test
    public void t1(){
        String key = "key1";
        System.out.println("插入数据到redis");
        redisTemplate.opsForValue().set(key,"value1");
        Object value = redisTemplate.opsForValue().get(key);
        System.out.println("从redis中获取到值为 "+value);
        Boolean delete = redisTemplate.delete(key);
        System.out.println("删除redis中值 "+delete);
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 概述 Redis是一个高性能的key-value数据库,它支持丰富的数据结构,如字符串、哈希、列表、集合、有序集合等。在实际应用中,为了提高Redis的可用性和扩展性,我们常常使用Redis集群。 本文将介绍如何在Spring Boot项目中集成Redis集群。 2. 环境准备 本文使用的环境如下: - JDK 1.8 - Spring Boot 2.3.8.RELEASE - Redis 5.0.10 - Redis集群 3. 集成Redis集群 3.1. 添加依赖 首先,在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.5.2</version> </dependency> ``` 其中,spring-boot-starter-data-redisSpring BootRedis的支持,jedis是Redis的Java客户端。 3.2. 配置Redis集群 在application.properties文件中添加如下配置: ``` # Redis集群配置 spring.redis.cluster.nodes=192.168.0.101:7001,192.168.0.101:7002,192.168.0.101:7003,192.168.0.102:7004,192.168.0.102:7005,192.168.0.102:7006 spring.redis.cluster.max-redirects=3 ``` 其中,spring.redis.cluster.nodes指定了Redis集群中所有节点的地址和端口,多个节点之间用逗号分隔,spring.redis.cluster.max-redirects指定了Redis客户端在执行命令时最多可以重定向的次数,一般设置为3即可。 3.3. 编写代码 在代码中使用Redis时,可以通过注入RedisTemplate来操作RedisRedisTemplate是SpringRedisTemplate的封装,使用起来非常方便。 ```java @Service public class RedisService { @Autowired private RedisTemplate<String, Object> redisTemplate; public void set(String key, Object value) { redisTemplate.opsForValue().set(key, value); } public Object get(String key) { return redisTemplate.opsForValue().get(key); } public void delete(String key) { redisTemplate.delete(key); } } ``` 上述代码中,我们定义了一个RedisService类,其中使用了@Autowired注解注入RedisTemplate,并提供了set、get、delete等操作Redis的方法。 4. 测试 在集成Redis集群Spring Boot项目中,我们可以通过调用RedisService中的方法来操作Redis。下面是一个简单的测试用例: ```java @SpringBootTest class RedisClusterApplicationTests { @Autowired private RedisService redisService; @Test void testRedis() { String key = "name"; String value = "John"; // 设置值 redisService.set(key, value); // 获取值 Object result = redisService.get(key); System.out.println(result); // 删除值 redisService.delete(key); } } ``` 在测试用例中,我们首先使用redisService.set方法将一个键值对存入Redis中,然后使用redisService.get方法获取值,并打印出来,最后使用redisService.delete方法删除该键值对。 5. 总结 本文介绍了在Spring Boot项目中集成Redis集群的方法,主要包括添加依赖、配置Redis集群和编写代码等步骤。通过本文的学习,相信大家已经掌握了Spring Boot集成Redis集群的基本方法,可以在实际项目中应用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值