springboot连接多个redis

2023-11-19

前言

我想不到,就这个问题还折腾了好一会儿

方法

yml配置文件

spring:
  application:
    name: multiredis
  redis:
    onedb:
      host: 192.168.2.1
      port: 6379
      password: 123456
      database: 10
      timeout: 5000
    threedb:
      host: 192.168.2.79
      port: 6379
      password: 654321
      database: 0
      timeout: 5000
    sixdb:
      host: 192.168.3.24
      port: 6379
      password: 123456
      database: 17
      timeout: 5000
server:
  port: 10556

创建

package com.example.multiredis;

import org.springframework.beans.factory.annotation.Qualifier;
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.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class RedisTemplateConfig {
    //onedb
    @Value("${spring.redis.onedb.host}")
    private String oneHost;
    @Value("${spring.redis.onedb.port}")
    private Integer onePort;
    @Value("${spring.redis.onedb.password}")
    private String onePassword;
    @Value("${spring.redis.onedb.database}")
    private Integer oneDatabase;

    //threedb
    @Value("${spring.redis.threedb.host}")
    private String threeHost;
    @Value("${spring.redis.threedb.port}")
    private Integer threePort;
    @Value("${spring.redis.threedb.password}")
    private String threePassword;
    @Value("${spring.redis.threedb.database}")
    private Integer threeDataBase;

    //sixdb
    @Value("${spring.redis.sixdb.host}")
    private String sixHost;
    @Value("${spring.redis.sixdb.port}")
    private Integer sixPort;
    @Value("${spring.redis.sixdb.password}")
    private String sixPassword;
    @Value("${spring.redis.sixdb.database}")
    private Integer sixDatabase;

    private static final int MAX_IDLE = 200; //最大空闲连接数
    private static final int MAX_TOTAL = 1024; //最大连接数
    private static final long MAX_WAIT_MILLIS = 10000; //建立连接最长等待时间


    //配置工厂
    public RedisConnectionFactory connectionFactory(String host, int port, String password, int maxIdle,
                                                    int maxTotal, long maxWaitMillis, int index) {
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
        jedisConnectionFactory.setHostName(host);
        jedisConnectionFactory.setPort(port);

        if (!StringUtils.isEmpty(password)) {
            jedisConnectionFactory.setPassword(password);
        }

        if (index != 0) {
            jedisConnectionFactory.setDatabase(index);
        }

        jedisConnectionFactory.setPoolConfig(poolConfig(maxIdle, maxTotal, maxWaitMillis, false));
        jedisConnectionFactory.afterPropertiesSet();
        return jedisConnectionFactory;
    }

    //连接池配置
    public JedisPoolConfig poolConfig(int maxIdle, int maxTotal, long maxWaitMillis, boolean testOnBorrow) {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(maxIdle);
        poolConfig.setMaxTotal(maxTotal);
        poolConfig.setMaxWaitMillis(maxWaitMillis);
        poolConfig.setTestOnBorrow(testOnBorrow);
        return poolConfig;
    }


    @Bean(name = "redisTemplate1")
    public StringRedisTemplate redisTemplate1() {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(
                connectionFactory(oneHost, onePort, onePassword, MAX_IDLE, MAX_TOTAL, MAX_WAIT_MILLIS, oneDatabase));
        return template;
    }

    @Bean(name = "redisTemplate3")
    public StringRedisTemplate redisTemplate3() {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(
                connectionFactory(threeHost, threePort, threePassword, MAX_IDLE, MAX_TOTAL, MAX_WAIT_MILLIS, threeDataBase));
        return template;
    }

    @Bean(name = "redisTemplate6")
    public StringRedisTemplate redisTemplate6() {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(
                connectionFactory(sixHost, sixPort, sixPassword, MAX_IDLE, MAX_TOTAL, MAX_WAIT_MILLIS, sixDatabase));
        return template;
    }
}

参考
注意:里面的代码有点过时了

使用

package com.example.multiredis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController  //返回字符串
public class HelloController {
    final
    StringRedisTemplate oneRedis;
    final
    StringRedisTemplate threeRedis;
    final
    StringRedisTemplate sixRedis;

    public HelloController(@Qualifier("redisTemplate1")StringRedisTemplate oneRedis,
                           @Qualifier("redisTemplate3")StringRedisTemplate threeRedis,
                           @Qualifier("redisTemplate6")StringRedisTemplate sixRedis) {

        this.oneRedis = oneRedis;
        this.threeRedis = threeRedis;
        this.sixRedis = sixRedis;
    }


    @RequestMapping("/hello")
    public String getTest(){
        String t_value = threeRedis.opsForValue().get("861675040628601");
        return "helloworld:"+ t_value+"--"+Math.random();
    }

}

注意里面的 @Qualifier 注解。不然会报错的。

方式二
这种方式,在IDEA使用@Autowired,会报黄(但是能用)。因为spring最新版,推荐的注入方式是构造函数注入

    @Autowired
    @Resource(name = "redisTemplate1")
    StringRedisTemplate  oneRedis;
    @Autowired
    @Resource(name = "redisTemplate3")
    StringRedisTemplate threeRedis;
    @Autowired
    @Resource(name = "redisTemplate6")
    StringRedisTemplate sixRedis;

参考2

原生说明

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/doushou?serverTimezone=UTC&useSSL=false
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
  data:
    mongodb:
      uri: mongodb://robin:123456@192.168.7.32/doushou
  redis:
    host: zhangsan.com
    port: 6379
    password: 222222
    database: 7
    timeout: 500

server:
  port: 12188

springboo 有默认的加载redis配置的方式,它自动化处理了,帮你隐藏了很多东西。
然后就写到唯一的里面了

@Autowired
    private RedisTemplate redisTemplate;

总结

受够了。感觉就是在纠结配置文件和语法糖。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

springboot连接多个redis 的相关文章

随机推荐

  • 循环的断点调试,指定第几次循环

    循环的断点调试 指定第几次循环 右击断点添加条件 断点要设置在条件之后 例如本次 想要i 3的时候的循环 条件要设到i后边 令i 3 回车 再按F5即可
  • CSS 学习笔记(基础)

    用来控制网页表现的语言 CSS Cascading Style Sheet 层叠样式表 然后我们继续看看 W3C 标准 结构 HTML 表现 CSS 行为 JavaScript CSS导入方式 选择器 属性 由于网页的框架结构是由HTML实
  • pydantic学习与使用 ------ 基本模型(BaseModel)使用

    前言 在 pydantic 中定义对象的主要方法是通过模型 模型继承 BaseModel pydantic主要是一个解析库 而不是验证库 验证是达到目的的一种手段 建立一个符合所提供的类型和约束的模型 换句话说 pydantic保证输出模型
  • Google FlatBuffers——开源、跨平台的新一代序列化工具

    前段时间刚试用了一个序列化工具cereal 请看 cereal C 实现的开源序列化库 打算再总结下我对google proto buf序列化库的使用呢 结果还没动手 大Google又出了一个新的 开源 跨平台的序列化工具 FlatBuff
  • ubuntu14 扩容的痛苦经历,在这里为大家献上我的过程(附带有gparted-live-0.25.0-3-i686下载地址)

    参考文档 https www linuxidc com Linux 2015 08 121674 htm VMware11下对虚拟机Ubuntu14 10系统所在分区sda1进行磁盘扩容 http www nxpic org module
  • CSS 语法

    CSS 规则集 rule set 由选择器和声明块组成 选择器指向您需要设置样式的 HTML 元素 声明块包含一条或多条用分号分隔的声明 每条声明都包含一个 CSS 属性名称和一个值 以冒号分隔 多条 CSS 声明用分号分隔 声明块用花括号
  • 提高情商6步法

    目录 1 识别与洞察 2 自制与表达 3 共情与共鸣 4 尊重与善意 5 认同与化解 戈尔曼把情商概括为以下五个方面的能力 认识自身情绪的能力 妥善管理情绪的能力 自我激励的能力 认识他人情绪的能力 管理人际关系的能力 1 识别与洞察 感知
  • Linux环境 Mysql安装详解

    Linux环境 Mysql安装详解 前言 mysql作为被广泛使用的数据库 安装的必要性是无需质疑的 而本人在多次安装中遇到了情况各异的问题 所以想以这篇文章记录一下安装配置的过程 并且尽量详细介绍每一步的原因 如果再遇到问题 知其然且知其
  • Inno打包后开始运行前检查文件是否存在

    Code function FileDoesNotExist file string Boolean begin if FileExists file then begin Result False end else begin Resul
  • Javascript高级程序设计——4.运算符

    运算符 1 一元运算符 2 算术运算符 3 关系运算符 4 相等运算符 全等运算符 5 逻辑运算符 6 位运算符 省略 不详细介绍 7 赋值运算符 8 其他运算符 9 运算符优先级 在ECMAScript与众不同之处在于 运算符可以适用于很
  • Centos7——MHA部署

    目录 基础操作 master操作 slave1操作 slave2操作 manager操作 测试 MHA 故障转移 连续漂移 实现主宕机 从切换为主 保证业务正常运行 环境准备 CentOS Linux release 7 5 1804 Co
  • TSI系统测量参数之:轴向振动

    一 TSI系统测量参数 1 轴向位移 2 盖振或瓦振 3 偏心 4 键相 5 零转速 6 轴向振动 7 相对热膨胀 胀差 8 绝对热膨胀 缸胀 二 各参数作用 2 轴向振动 测量的是大轴相对于轴瓦的X向振动和Y向振动 反馈电压量程为 4V至
  • TikTok已达万粉,开通基金仍失败?--TK领航社TIKTOK运营变现最新干货分享

    播神定期分享TikTok运营技巧 教你从零快速掌握TikTok运营和商业变现 今天与大家探讨下 TikTok已达万粉 创作者基金依旧开通失败 是为什么 TK领航社 国内最大TIKTOK社群 运营变现圈子 TikTok 创作者基金是为回馈优质
  • 如何简单快速的探测民用无人机?

    前言 最近俄乌冲突搞得火热 其中以DJI 无人机为代表的民用无人机表现尤为引人注意 这不禁让人思考 在此类无人机战争中步兵班应如何有效快速的感知民用无人机的存在 提高生存能力 一 民用无人机在冲突中的优势 从目前能搜集到的信息来看有以下几个
  • 软件测试-金融银行项目怎么测?系统业务测试总结分析...

    目录 导读 前言 一 Python编程入门到精通 二 接口自动化项目实战 三 Web自动化项目实战 四 App自动化项目实战 五 一线大厂简历 六 测试开发DevOps体系 七 常用自动化测试工具 八 JMeter性能测试 九 总结 尾部小
  • 计算机的保护模式与实模式

    一 背景 80386开始 CPU有三种工作方式 实模式 保护模式和虚拟8086模式 只有在刚刚启动的时候是real mode 等到操作系统运行起来以后就切换到protected mode 实模式只能访问地址在1M以下的内存称为常规内存 我们
  • java ssm常遇见的问题_ssm增删改查出现的问题总结

    1 org springframework beans factory BeanCreationException Error creating bean with name org mybatis spring mapper Mapper
  • python 多进程进行文件处理(一)

    在文件处理的时候 经常会遇见大文件数据 单进程处理速度太慢 可以通过多进程来提升效率 应用场景一 同时并行处理多个小文件 处理完成后 写回多个文件 def read wiki data infile outfile param1 单个文件的
  • 【ROS】usb_cam相机标定

    1 唠叨两句 当我们要用相机做测量用途时 就需要做相机标定了 不然得到的计算结果会有很大误差 标定的内容包括三部分 内参 外参还有畸变参数 所以标定的过程就是要求得上面这些参数 以前弄这个事估计挺麻烦 需要做实验和计算才能得到 现在通过ro
  • springboot连接多个redis

    文章目录 前言 方法 yml配置文件 使用 原生说明 总结 前言 我想不到 就这个问题还折腾了好一会儿 方法 yml配置文件 spring application name multiredis redis onedb host 192 1