SpringBoot项目,配置Redis多数据源

一、maven依赖

Springboot版本: 1.5.6.RELEASE
<!--redis-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--多数据源-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

二、redis配置文件

2.1 application.yml
spring:
  redis:
    host: xxx.xxx.xxx.xxx
    port: xxxx
    timeout: 0
    pool:
      max-active: 8
      max-wait: -1
      max-idle: 8
      min-idle: 0
  redis2:
    host: xxx.xxx.xxx.xxx
    port: xxxx
    timeout: 0
2.2 redis配置类通用父类

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Created by liruigao
 * Date: 2020-06-01 13:54
 * Description:
 */

@EnableCaching
@Configuration
public class CommonRedisConfig {
    @Value("${spring.redis.pool.max-active}")
    private int redisPoolMaxActive;

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

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

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

    /**
     * 配置CacheManager
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
        return redisCacheManager;
    }

    /**
     * 创建redis连接工厂
     *
     * @param host
     * @param port
     * @param timeout
     * @return
     */
    public RedisConnectionFactory createJedisConnectionFactory(String host, int port, int timeout) {
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
        jedisConnectionFactory.setHostName(host);
        jedisConnectionFactory.setPort(port);
        jedisConnectionFactory.setTimeout(timeout);
        jedisConnectionFactory.setPoolConfig(setPoolConfig(redisPoolMaxIdle, redisPoolMinIdle,
                redisPoolMaxActive, redisPoolMaxWait));
        return jedisConnectionFactory;

    }

    /**
     * 设置连接池属性
     *
     * @param maxIdle
     * @param minIdle
     * @param maxActive
     * @param maxWait
     * @return
     */
    public JedisPoolConfig setPoolConfig(int maxIdle, int minIdle, int maxActive, int maxWait) {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(maxIdle);
        poolConfig.setMinIdle(minIdle);
        poolConfig.setMaxTotal(maxActive);
        poolConfig.setMaxWaitMillis(maxWait);
        return poolConfig;
    }
}
2.3 redis配置类1

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.Map;

/**
 * Created by liruigao
 * Date: 2020-06-01 15:30
 * Description:
 */

@Configuration
public class TestRedisConfig extends CommonRedisConfig{
    @Value("${spring.redis2.host}")
    private String host2;

    @Value("${spring.redis2.port}")
    private int port2;

    @Value("${spring.redis2.timeout}")
    private int timeout2;

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

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

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

    /**
     * 此bean为必要的,RedisConnectionFactory默认配置项
     * 凡是未指明RedisConnectionFactory的redis配置类,均默认注入此bean
     * @return
     */
    @Primary
    @Bean(name = "defaultRedisConnectionFactory")
    public RedisConnectionFactory defaultRedisConnectionFactory() {
        return createJedisConnectionFactory(host, port, timeout);
    }

    @Bean(name = "secondRedisConnectionFactory")
    public RedisConnectionFactory secondRedisConnectionFactory() {
        return createJedisConnectionFactory(host2, port2, timeout2);
    }

    @Bean("testRedisTemplate")
    public RedisTemplate<String, String> testRedisTemplate() {
        RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(secondRedisConnectionFactory());
        redisTemplate.setDefaultSerializer(new StringRedisSerializer());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    @Bean("testHmsetTemplate")
    public RedisTemplate<String, Map<String, String>> testHmsetTemplate() {
        RedisTemplate<String, Map<String, String>> hmsetTemplate = new RedisTemplate<>();
        hmsetTemplate.setConnectionFactory(secondRedisConnectionFactory());
        hmsetTemplate.setDefaultSerializer(new StringRedisSerializer());
        hmsetTemplate.afterPropertiesSet();
        return hmsetTemplate;
    }
}
2.4 redis配置类2

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.StringRedisSerializer;

import java.util.Map;

/**
 * Created by liruigao
 * Date: 2020-04-22 17:41
 * Description:
 */

@Configuration
public class RedisConfig {

    // 默认注入defaultRedisConnectionFactory
    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setDefaultSerializer(new StringRedisSerializer());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    @Bean
    public RedisTemplate<String, Map<String, String>> hmsetTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Map<String, String>> hmsetTemplate = new RedisTemplate<>();
        hmsetTemplate.setConnectionFactory(redisConnectionFactory);
        hmsetTemplate.setDefaultSerializer(new StringRedisSerializer());
        hmsetTemplate.afterPropertiesSet();
        return hmsetTemplate;
    }
}

三、redis通用方法类

3.1 redis通用方法类1

import com.baidu.neisou.forward.core.utils.LoggerHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * redis基础工具类
 */
@Component("TestRedisService")
public class TestRedisService {

    @Autowired
    private RedisTemplate<String, String> testRedisTemplate;

    @Autowired
    private RedisTemplate<String, Map<String, String>> testHmsetTemplate;

    /**
     * 读取缓存k
     *
     * @param key
     * @return
     */
    public String get(final String key) {
        String result = null;
        try {
            ValueOperations<String, String> operations = testRedisTemplate.opsForValue();
            result = operations.get(key);
        } catch (Exception e) {
            LoggerHelper.err(getClass(), "redis get error! key:{}, e:{}", key, e);
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public void set(final String key, String value, Long expireTime) {
        try {
            ValueOperations<String, String> operations = testRedisTemplate.opsForValue();
            operations.set(key, value);
            // 负数过期时间则永不过期
            if (expireTime != null && expireTime > 0L) {
                testRedisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            }
        } catch (Exception e) {
            LoggerHelper.err(getClass(), "redis set error! key:{}, value:{}, e:{}", key, value, e);
            e.printStackTrace();
        }
    }

    /**
     * hset
     *
     * @param key
     * @param field
     * @param value
     * @return
     */
    public boolean hset(String key, String field, String value, long... expire) {
        boolean result = false;
        try {
            final byte[] rawKey = testRedisTemplate.getStringSerializer().serialize(key);
            final byte[] rawField = testRedisTemplate.getStringSerializer().serialize(field);
            final byte[] rawValue = testRedisTemplate.getStringSerializer().serialize(value);
            result = testRedisTemplate.execute(new RedisCallback<Boolean>() {
                public Boolean doInRedis(RedisConnection connection) {
                    boolean ret = connection.hSet(rawKey, rawField, rawValue);
                    if (expire.length > 0 && expire[0] > 0) {
                        connection.expire(rawKey, expire[0]);
                    }
                    return ret;
                }
            }, true);
        } catch (Exception e) {
            LoggerHelper.err(getClass(), "hset error, key : {}, field : {}, value : {}, e : {}",
                    key, field, value, e);
        }
        return result;
    }

    /**
     * hget
     *
     * @param key
     * @param field
     * @return
     */
    public String hget(String key, String field) {
        final byte[] rawKey = testRedisTemplate.getStringSerializer().serialize(key);
        final byte[] rawField = testRedisTemplate.getStringSerializer().serialize(field);
        final byte[] rawValue = testRedisTemplate.execute(new RedisCallback<byte[]>() {
            public byte[] doInRedis(RedisConnection connection) {
                return connection.hGet(rawKey, rawField);
            }
        }, true);
        return testRedisTemplate.getStringSerializer().deserialize(rawValue);
    }

    public void expire(String key, long livetime) {
        testRedisTemplate.expire(key, livetime, TimeUnit.SECONDS.SECONDS);
    }

    /**
     * hmset
     * @param key
     * @param map
     * @param expire
     * @return
     */
    public void hmset(String key, Map<String, String> map, long... expire) {
        try {
            testHmsetTemplate.opsForHash().putAll(key, map);
            if (expire.length > 0 && expire[0] > 0) {
                expire(key, expire[0]);
            }
        } catch (Exception e) {
            LoggerHelper.err(getClass(), "hmset error, key : {}, map : {}, e : {}", key, map, e);
        }
    }

}
3.2 redis通用方法类2
package com.baidu.neisou.forward.manager.redis;

import com.baidu.neisou.forward.core.utils.LoggerHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * redis基础工具类
 */
@Service("RedisService")
public class RedisService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private RedisTemplate<String, Map<String, String>> hmsetTemplate;

    /**
     * 读取缓存k
     *
     * @param key
     * @return
     */
    public String get(final String key) {
        String result = null;
        try {
            ValueOperations<String, String> operations = redisTemplate.opsForValue();
            result = operations.get(key);
        } catch (Exception e) {
            LoggerHelper.err(getClass(), "redis get error! key:{}, e:{}", key, e);
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public void set(final String key, String value, Long expireTime) {
        try {
            ValueOperations<String, String> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            // 负数过期时间则永不过期
            if (expireTime != null && expireTime > 0L) {
                redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            }
        } catch (Exception e) {
            LoggerHelper.err(getClass(), "redis set error! key:{}, value:{}, e:{}", key, value, e);
            e.printStackTrace();
        }
    }

    /**
     * hset
     *
     * @param key
     * @param field
     * @param value
     * @return
     */
    public boolean hset(String key, String field, String value, long... expire) {
        boolean result = false;
        try {
            final byte[] rawKey = redisTemplate.getStringSerializer().serialize(key);
            final byte[] rawField = redisTemplate.getStringSerializer().serialize(field);
            final byte[] rawValue = redisTemplate.getStringSerializer().serialize(value);
            result = redisTemplate.execute(new RedisCallback<Boolean>() {
                public Boolean doInRedis(RedisConnection connection) {
                    boolean ret = connection.hSet(rawKey, rawField, rawValue);
                    if (expire.length > 0 && expire[0] > 0) {
                        connection.expire(rawKey, expire[0]);
                    }
                    return ret;
                }
            }, true);
        } catch (Exception e) {
            LoggerHelper.err(getClass(), "hset error, key : {}, field : {}, value : {}, e : {}",
                    key, field, value, e);
        }
        return result;
    }

    /**
     * hget
     *
     * @param key
     * @param field
     * @return
     */
    public String hget(String key, String field) {
        final byte[] rawKey = redisTemplate.getStringSerializer().serialize(key);
        final byte[] rawField = redisTemplate.getStringSerializer().serialize(field);
        final byte[] rawValue = redisTemplate.execute(new RedisCallback<byte[]>() {
            public byte[] doInRedis(RedisConnection connection) {
                return connection.hGet(rawKey, rawField);
            }
        }, true);
        return redisTemplate.getStringSerializer().deserialize(rawValue);
    }

    public void expire(String key, long livetime) {
        redisTemplate.expire(key, livetime, TimeUnit.SECONDS.SECONDS);
    }

    /**
     * hmset
     * @param key
     * @param map
     * @param expire
     * @return
     */
    public void hmset(String key, Map<String, String> map, long... expire) {
        try {
            hmsetTemplate.opsForHash().putAll(key, map);
            if (expire.length > 0 && expire[0] > 0) {
                expire(key, expire[0]);
            }
        } catch (Exception e) {
            LoggerHelper.err(getClass(), "hmset error, key : {}, map : {}, e : {}", key, map, e);
        }
    }
}

四、测试用例


import com.baidu.neisou.forward.manager.redis.RedisService;
import com.baidu.neisou.forward.manager.redis.TestRedisService;
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.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * Created by liruigao
 * Date: 2020-04-10 14:38
 * Description:
 */
//@Ignore
@SpringBootTest(classes = App.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class RedisServiceTest {
    @Autowired
    private RedisService redisService;
    @Autowired
    private TestRedisService testRedisService;

    @Test
    public void diffRedisTest() {
        redisService.set("test", "default redis");
        testRedisService.set("test", "second redis");
        String rlt1 = redisService.get("test");
        String rlt2 = testRedisService.get("test");
        System.out.println("redisService.get : " + rlt1);
        System.out.println("testRedisService.get : " + rlt2);

    }
}

result:

redisService.get : default redis
testRedisService.get : second redis
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
# 简介 springboot-skeleton 是一个基于SpringBoot,快速构建微服务项目的脚手架。内置mybatis-plus、alibaba-druid、xxl-job、redis、rocketMq等基础组件,并且包括了这些基础组件的使用demo; 本项目master分支作为基础脚手架,包括大家平时常用的基础依赖包,非常用包例如分库分表、多数据源等场景会通过特色分支来建设 # 功能特点 - [x] 基于Eureka注册中心 - [x] swagger 接口文档生成 - [x] 基于xxl-job的分布式任务调度器 - [x] ORM代码自动生成 - [x] 参数优雅验证 - [x] druid数据库连接池; - [x] 连接池监控UI; - [x] sharding-jdbc 分库分表中间件 - [x] 链路追踪组件 - [x] 配置中心 - [x] 分布式锁 redission # 核心组件 - [x] Skywalking - [x] Swagger-Ui - [x] Mybatis-plus - [x] Druid - [x] Eureka - [x] Xxl-job - [x] Sharding-jdbc - [x] hutool - [x] Redis - [ ] Nacos - [ ] RocketMq - [ ] Easypoi - [ ] OSS # 使用方式 待完善 ## 项目备注 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.md文件(如有),仅供学习参考, 切勿用于商业用途。
# Geek-Framework 微服务快速开发脚手架 ### 平台简介 Geek-Framework是基于多个优秀的开源项目,高度整合封装而成的高效,高性能,强安全性的**开源**Java微服务快速开发框架。 Geek-Framework是在SpringBoot基础上搭建的一个Java基础开发框架,以Spring MVC为模型视图控制器,MyBatis为数据访问层, Apache Shiro和Spring-Security为权限授权层,redis进行缓存。 Geek-Framework主要定位于微应用的开发,已内置后台系统的基础功能,用户管理、角色管理、权限管理、会员管理、日志管理等;前台已经实现用户登录,注册等基础功能。 同时前后台会员实现分表管理,可扩展多角色系统、多权限系统。 采用分层设计、双重验证、提交数据安全编码、密码加密、访问验证、数据权限验证。 使用Maven做项目管理,提高项目的易开发性、扩展性。 --- ###更新日期2019-01-16 * 升级springboot版本为2.1.2.RELEASE application.yml增加以下配置,兼容最新的springboot版本 > spring:main:allow-bean-definition-overriding: true * 移除j2cache支持,移除原因为简化新手用户部署系统配置 * 更改后台登录为单realm,不再支持多realm * 优化日期时间工具类,使用Instant、LocalDateTime、LocalDate实现线性安全 * 修复Java开发规约中级警告及部分低级警告 * 增加debug日志输出开关 ###更新日期2018-12-28 * 项目增加健康检查暴露配置 * 根据JAVA开发手册对项目部分不符合开发手册的代码进行了修正,已修复高级警告、中级警告,由于低级警告较多,尚未修复,后续将持续修复 * 给前期已经使用项目的同学,可以使用【阿里巴巴Java开发规约插件p3c】进行修正,造成不便深表歉意 ###更新日期2018-10-08 * 最近学习了远程过程调用协议RPC(Remote Procedure Call Protocol),将本框架与dubbo做了一个集成,详见dubbo分支, * 为了方便大学家习dubbo的运行机制,本框架将dubbo的provider和customer作了一个整合,将官方demo里的方多应用整合成了一个,即在同一应用内启动消费端和服务端 * 注:如有实际业务需要请将服务端与消费端分离,此处整合仅供学习dubbo的运行机制和思想 ###更新日期2018-09-19 * 升级mybatis包为mybatis-spring-boot-starter,移除原有mybatis包 * 升级mapper包为mapper-spring-boot-starter * 升级pagehelper包为pagehelper-spring-boot-starter增加pagehelper-spring-boot-autoconfigure包 * 更改mybatis、mapper和pagehelper为自动配置配置方式详见application.yml * 移除MyBatisConfig.java和MybatisMapperScannerConfig.java文件 * 更改升级pagehelper之后对排序方式的处理方式 * 增加事务测试样例,详见AdminController的save方法,此坑很深,爬了一天,由于没有对spring事务的深入了解,导致事务一直不成功,原因在于spring事务只能处理没有被捕获的异常信息,如果对方法增加了事务,请尽量避免用catch来获取异常,或进在cache里面增加抛出异常功能,使事务能够访问到 ###更新日期2018-09-19 * 升级J2cache为2.7.0版本,主要修复channel获取次数过多导致的错误问题,另个j2cache后期可能会移除对jedis的支持,所以还是提前升级了吧 * 调整二级缓存redis为lettuce,lettuce为spring推荐的redis操作方式,另个 ## 项目备注 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.md文件(如有),仅供学习参考, 切勿用于商业用途。
# springboot 集成第三方框架测试学习 ~~~ springboot 2.0.4版本以上需配置数据源不然启动会报错或者启动类取消数据源自动注入(加入注解@EnableAutoConfiguration(exclude = DataSourceAutoConfiguration.class)) ~~~ * [springboot配置学习](https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-spring-application) ## 目前已经加入集成成功的demo * [SpringBoot+elasticsearch](./springboot-elasticsearch/README.md) * [SpringBoot+elasticsearch7.x](./springboot-elasticsearch7/README.md) * [SpringBoot+tkmapper](./springboot-tkmapper/README.md) * [SpringBoot+rabbitmq](./springboot-rabbitmq/README.md) * [SpringBoot+kafka](./springboot-kafka) * [SpringBoot+shiro(REAMDME.md RBAC 参考链接)](./springboot-shiro/README.md) * [SpringBoot+redis](./springboot-redis/README.md) * [SpringBoot+security](./springboot-security/README.md) * [SpringBoot+simple_security](./springboot-simple-security/README.md) * [SpringBoot+seaweedfs](./springboot-seaweedfs/README.md) ## 待测试 * [SpringBoot-fastdfs](./springboot-fdfs/README.md) ## 项目备注 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.md文件(如有),仅供学习参考, 切勿用于商业用途。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

喜鹊先生Richard

随缘~

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

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

打赏作者

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

抵扣说明:

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

余额充值