springboot项目同时操作redis服务器的两个库以及操作两个redis实例

本文详细介绍如何在Spring Boot项目中配置两个Redis实例,并分别指定不同的数据库,包括配置文件及核心配置类。

本文介绍的有两种连接方式:1.操作一个redis实例的不同库。2.操作两个redis实例的库【这种情况相同不同都一样】,两种方法大差不差,基于一个大致的框架上小改即可实现。

先说第一种情况:

一、搭建项目

搭建项目比较简单,idea可以自动生成,这里只放pom.xml【依赖是我项目用到的,根据自己情况改】

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.siemens</groupId>
    <artifactId>gat</artifactId>
    <version>0.0.1</version>
    <name>gat</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.1.42</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-joda</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-parameter-names</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <version>1.3.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.6.0</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

二、application.yml文件配置

server:
  port: 8081

spring:
  datasource:
    name: druid_source
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/databaseName?characterEncoding=utf8&useSSL=false&serverTimezone=CTT&allowPublicKeyRetrieval=true
    username: xxxx
    password: xxxx

#配置0号库和10号库
redis:
  database:
    db1: 0
    db2: 10
  host: 127.0.0.1
  port: 6379
  timeout: 10000
  pool:
    max-active: 100
    max-idle: 3
    min-idle: 0
    max-wait: -1

三、redis配置类

package com.siemens.gat.config;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.Duration;

/**
 * Created by SongShilun on 2020/12/14 10:12
 */
@Configuration
public class RedisConfig {
    @Value("${redis.database.db1}")
    private int db1;

    @Value("${redis.database.db2}")
    private int db2;

    @Value("${redis.host}")
    private String host;

    @Value("${redis.port}")
    private int port;

    @Value("${redis.timeout}")
    private int timeout;

    @Value("${redis.pool.max-active}")
    private int maxActive;

    @Value("${redis.pool.max-idle}")
    private int maxIdle;

    @Value("${redis.pool.min-idle}")
    private int minIdle;

    @Value("${redis.pool.max-wait}")
    private int maxWait;

    @Bean
    public GenericObjectPoolConfig getPoolConfig(){
        // 配置redis连接池
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxTotal(maxActive);
        poolConfig.setMaxIdle(maxIdle);
        poolConfig.setMinIdle(minIdle);
        poolConfig.setMaxWaitMillis(maxWait);
        return poolConfig;
    }

    @Bean(name = "redisTemplate1")
    public StringRedisTemplate getRedisTemplate1(){
        return getStringRedisTemplate(db1);
    }

    @Bean(name = "redisTemplate2")
    public StringRedisTemplate getRedisTemplate2(){
        return getStringRedisTemplate(db2);
    }

    private StringRedisTemplate getStringRedisTemplate(int database) {
        // 构建工厂对象
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
        config.setHostName(host);
        config.setPort(port);
        //config.setPassword(RedisPassword.of(password));
        LettucePoolingClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()
                .commandTimeout(Duration.ofSeconds(timeout))
                .poolConfig(getPoolConfig())
                .build();
        LettuceConnectionFactory factory = new LettuceConnectionFactory(config, clientConfig);
        // 设置使用的redis数据库
        factory.setDatabase(database);
        // 重新初始化工厂
        factory.afterPropertiesSet();
        return new StringRedisTemplate(factory);
    }
}

以上就是连接一个redis实例,分别操作一个redis实例的不同的两个库的配置

---------------------------------------------------------------分割线--------------------------------------------------------------

下边说一下,当需要连接两个不同服务器上的redis时,应该怎么配置:
ps:连接两个redis实例和上述的代码很像,只需要做些小小的改动即可:

  1. pom.xml文件不动
  2. application.yml:
server:
  port: 8081

spring:
  datasource:
    name: druid_source
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/databaseName?characterEncoding=utf8&useSSL=false&serverTimezone=CTT&allowPublicKeyRetrieval=true
    username: xxxx
    password: xxxx

#配置两个redis实例,第一个用0号库,用于读取并监控数据变化;第二个用10号库,用来存放数据变化的信息
redis1:
  database:
    db1: 0
  host: 127.0.0.1
  port: 6379
  timeout: 10000
  pool:
    max-active: 100
    max-idle: 3
    min-idle: 0
    max-wait: -1

redis2:
  database:
    db2: 10
  host: xxx.xxx.xx.xx
  port: 6379
  timeout: 10000
  pool:
    max-active: 100
    max-idle: 3
    min-idle: 0
    max-wait: -1
  1. redis配置类
package com.siemens.gat.config;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.Duration;

/**
 * Created by SongShilun on 2020/12/14 10:12
 */
@Configuration
public class RedisConfig {
    @Value("${redis1.database.db1}")
    private int db1;

    @Value("${redis2.database.db2}")
    private int db2;

    @Value("${redis1.host}")
    private String host1;

    @Value("${redis1.port}")
    private int port1;

    @Value("${redis1.timeout}")
    private int timeout;

    @Value("${redis1.pool.max-active}")
    private int maxActive;

    @Value("${redis1.pool.max-idle}")
    private int maxIdle;

    @Value("${redis1.pool.min-idle}")
    private int minIdle;

    @Value("${redis1.pool.max-wait}")
    private int maxWait;


    @Value("${redis2.host}")
    private String host2;
    @Value("${redis2.port}")
    private int port2;

    @Bean
    public GenericObjectPoolConfig getPoolConfig(){
        // 配置redis连接池
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxTotal(maxActive);
        poolConfig.setMaxIdle(maxIdle);
        poolConfig.setMinIdle(minIdle);
        poolConfig.setMaxWaitMillis(maxWait);
        return poolConfig;
    }

    @Bean(name = "redisTemplate1")
    public StringRedisTemplate getRedisTemplate1(){
        return getStringRedisTemplate(db1,host1,port1);
    }

    @Bean(name = "redisTemplate2")
    public StringRedisTemplate getRedisTemplate2(){
        return getStringRedisTemplate(db2,host2,port2);
    }

    private StringRedisTemplate getStringRedisTemplate(int database,String address,int portNum) {
        // 构建工厂对象
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
        config.setHostName(address);
        config.setPort(portNum);
        //config.setPassword(RedisPassword.of(password));
        LettucePoolingClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()
                .commandTimeout(Duration.ofSeconds(timeout))
                .poolConfig(getPoolConfig())
                .build();
        LettuceConnectionFactory factory = new LettuceConnectionFactory(config, clientConfig);
        // 设置使用的redis数据库
        factory.setDatabase(database);
        // 重新初始化工厂
        factory.afterPropertiesSet();
        return new StringRedisTemplate(factory);
    }
}

可以看出来,相比于连接一个redis实例的不同库,连接两个redis实例只多了application的一个配置信息,和对redis配置类的工厂化方法的小改动。一个redis默认有下标为0-15的16个库,连接一个实例的不同库和连接两个实例的相同库,以及连接两个实例的不同库,其原理都是相同的,只要做通一个功能,其余的功能可以基于原有的功能上进行修改。

<think>首先,用户的问题是:“我想查找springboot项目支持redis配置非 default 账号的方法 请问springboot项目支持redis配置非 default 账号的解决方案”。 用户引用了两个来源: - 引用[1]:描述了后端技术栈,包括Redis配置。 - 引用[2]:详细说明了Spring Boot连接Redis的两种方式:传统host/port方式和URL方式。URL方式支持用户名,适用于Redis 6.0及更高版本,因为它支持ACL(Access Control List)。 关键点是:用户想知道如何配置Spring Boot项目使用Redis的非default账号(即非默认账号)。Redis从6.0开始支持用户名(username),不再只是密码。 从引用[2]中,我了解到: - 传统方式:使用host、port、password,但不支持用户名。 - URL方式:使用格式如`redis://username:password@host:port/database`,这支持用户名。 所以,解决方案是使用URL方式来配置Redis连接,以指定非default账号。 我的回答需要: - 使用中文。 - 结构化清晰,逐步解决问题。 - 引用相关部分,末尾添加引用标识。 - 确保真实可靠:基于Spring Boot和Redis的官方文档。 - 生成相关问题(根据系统指令)。 步骤结构化回答: 1. **引言**:确认问题,并简要说明解决方案。 2. **解释解决方案**: - Redis 6.0引入了ACL,支持用户名。 - Spring Boot支持通过URL配置连接。 - 如何在Spring Boot中配置:使用`redis.url`属性。 3. **代码示例**:展示如何在`application.properties`或`application.yml`中配置。 4. **注意事项**:确保Redis版本兼容性(6.0+),密码处理等。 5. **引用**:自然添加引用标识到引用来源。 6. **生成相关问题**:基于此主题。 引用标识: - 引用[1]:整体技术栈,提到Redis。 - 引用[2]:提供具体配置细节,尤其是URL方式。 在回答中,我需要自然地引用[2],因为它直接相关。 相关问题生成(§§相关问题§§): 1. Redis ACL是什么? 2. 如何在Spring Boot中配置Redis集群? 3. Spring Boot Redis连接池配置优化? 确保LaTeX语法: - 所有数学表达式用$...$,但这里可能没有数学内容。 - 独立公式用$$...$$,同样可能不适用。 完整回答结构: - 回答部分。 - §§相关问题§§部分。 最终回答: </think>### Spring Boot项目支持Redis配置非default账号的解决方案 在Spring Boot项目中配置Redis使用非default账号(即指定用户名和密码),可以通过Redis的URL连接方式实现。Redis从6.0版本开始支持ACL(访问控制列表),允许设置用户名和密码。Spring Boot的`spring-boot-starter-data-redis`模块提供了灵活的支持。以下是逐步解决方案: #### 1. **确认Redis版本和依赖** - **Redis版本要求**:确保Redis服务器版本≥6.0,以支持用户名认证(ACL功能)。如果使用较低版本,只能配置密码(不支持用户名)。 - **Spring Boot依赖**:在`pom.xml`中添加Redis依赖(引用[1]中提到后端技术栈使用SpringBoot 2.7.x): ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` #### 2. **配置Redis连接URL** - **推荐方式**:使用URL格式配置连接,直接在Spring Boot配置文件中指定用户名、密码、主机和数据。URL格式为:`redis://username:password@host:port/database`。 - **示例配置**(在`application.yml`文件中): ```yaml spring: redis: url: "redis://your_username:your_password@examlp.com:6379/5" # 替换为实际用户名、密码和数据编号 ``` - 解释: - `your_username`:非default账号的用户名(如管理员创建的自定义账号)。 - `your_password`:对应用户名的密码(需确保密码正确)。 - `examlp.com:6379`:Redis服务器地址和端口。 - `/5`:指定连接的数据编号(可省略,默认为0)。 - **优势**:这种方式支持用户名认证,适用于ACL-enabled Redis实例[^2]。 - **传统方式局限性**:传统host/port配置(如引用[2]所示)仅支持密码,不支持用户名: ```yaml spring: redis: host: aaaa.rds.aliyuncs.com port: 6379 password: "your_password" # 仅密码,无用户名支持 database: 0 ``` 这种方法仅适用于default账号(用户名为"default"),无法指定自定义用户名。 #### 3. **处理特殊字符** - **密码转义**:如果密码包含特殊字符(如`@`或`:`),在URL中需进行URL编码(例如,`@`编码为`%40`)。Spring Boot会自动处理,但建议在配置中使用双引号包裹URL以避免YAML解析问题。 - 示例: ```yaml spring: redis: url: "redis://username:pass%40word@host:6379" # 密码中的@编码为%40 ``` #### 4. **验证配置** - **测试连接**:编写简单测试代码,检查Redis连接是否成功: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { @Autowired private StringRedisTemplate redisTemplate; @GetMapping("/test-redis") public String test() { redisTemplate.opsForValue().set("testKey", "Hello, Redis with non-default user!"); return "Redis connection successful. Value set: " + redisTemplate.opsForValue().get("testKey"); } } ``` - **常见错误**: - 如果Redis版本<6.0,URL方式会报错;升级Redis或回退到传统密码配置。 - 用户名或密码错误:检查Redis ACL设置(使用`redis-cli`命令验证账号)。 #### 注意事项 - **版本兼容性**:Spring Boot 2.7.x完全支持Redis 6.0+的URL配置(如引用[2]所述),无需额外依赖。 - **安全实践**:敏感信息(如密码)建议使用环境变量或Spring Cloud Config管理: ```yaml spring: redis: url: "redis://${REDIS_USERNAME}:${REDIS_PASSWORD}@host:6379" # 从环境变量读取 ``` - **引用来源**:此方案基于Spring Boot官方文档和Redis ACL特性,URL配置方式已在引用[2]中详细说明[^2]。
评论 3
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值