springboot集成redis配置多数据源
生活随笔
收集整理的這篇文章主要介紹了
springboot集成redis配置多数据源
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【前言】在開發需求中,很多情況一個數據源是不能夠滿足業務需求的,常常需要我們去配置多個數據源去綜合使用完成業務需要的功能
其實多數據源本質就是多個redisTemplate
【代碼】
1、依賴(這里以gradle項目為例)
這里需要注意的是jedis的版本要在2.7以上,低版本會出現類缺省問題
2、application配置
3、注入數據源
/*** @Author: LvFang* @Date: Created in 2018/7/25.* @Description:redis多數據源配置*/ @Configuration public class RedisReivceConfig {private static Logger logger = LoggerFactory.getLogger(ReceiverService.class);//---------------------------------------多數據源配置-----------------------------------------------------/*** redisDevTemplate 數據源*/@Bean(name = "redisDevTemplate")public StringRedisTemplate redisTemplate(@Value("${spring.redis.dev.host}") String hostName,@Value("${spring.redis.dev.port}") int port, // @Value("${spring.redis.dev.password}") String password,@Value("${spring.redis.dev.testOnBorrow}") boolean testOnBorrow,@Value("${spring.redis.dev.database}") int index,@Value("${spring.redis.pool.max-idle}") int maxIdle,@Value("${spring.redis.pool.max-active}") int maxTotal,@Value("${spring.redis.pool.max-wait}") long maxWaitMillis) {StringRedisTemplate temple = new StringRedisTemplate();temple.setConnectionFactory(connectionFactory(hostName, port, maxIdle, maxTotal, index, maxWaitMillis, testOnBorrow));return temple;}/*** redisTestTemplate 數據源*/@Bean(name = "redisTestTemplate")public StringRedisTemplate redisTemplate(@Value("${spring.redis.test.host}") String hostName,@Value("${spring.redis.test.port}") int port, // @Value("${spring.redis.test.password}") String password,@Value("${spring.redis.test.testOnBorrow}") boolean testOnBorrow,@Value("${spring.redis.test.database}") int index,@Value("${spring.redis.pool.max-idle}") int maxIdle,@Value("${spring.redis.pool.max-active}") int maxTotal,@Value("${spring.redis.pool.max-wait}") long maxWaitMillis) {StringRedisTemplate temple = new StringRedisTemplate();temple.setConnectionFactory(connectionFactory(hostName, port, maxIdle, maxTotal, index, maxWaitMillis, testOnBorrow));return temple;}/*** 有密碼*/public RedisConnectionFactory connectionFactory(String hostName, int port, String password, int maxIdle,int maxTotal, int index, long maxWaitMillis, boolean testOnBorrow) {JedisConnectionFactory jedis = new JedisConnectionFactory();jedis.setHostName(hostName);jedis.setPort(port);//如果密碼不為空才去設置密碼(如果沒有密碼,不設置或者設置空字符串即可)if (StringUtils.isNotEmpty(password)) {jedis.setPassword(password);}if (index != 0) {jedis.setDatabase(index);}jedis.setPoolConfig(poolCofig(maxIdle, maxTotal, maxWaitMillis, testOnBorrow));// 初始化連接pooljedis.afterPropertiesSet();RedisConnectionFactory factory = jedis;return factory;}/*** 無密碼*/public RedisConnectionFactory connectionFactory(String hostName, int port, int maxIdle,int maxTotal, int index, long maxWaitMillis, boolean testOnBorrow) {JedisConnectionFactory jedis = new JedisConnectionFactory();jedis.setHostName(hostName);jedis.setPort(port);if (index != 0) {jedis.setDatabase(index);}jedis.setPoolConfig(poolCofig(maxIdle, maxTotal, maxWaitMillis, testOnBorrow));// 初始化連接pooljedis.afterPropertiesSet();RedisConnectionFactory factory = jedis;return factory;}public JedisPoolConfig poolCofig(int maxIdle, int maxTotal, long maxWaitMillis, boolean testOnBorrow) {JedisPoolConfig poolCofig = new JedisPoolConfig();poolCofig.setMaxIdle(maxIdle);poolCofig.setMaxTotal(maxTotal);poolCofig.setMaxWaitMillis(maxWaitMillis);poolCofig.setTestOnBorrow(testOnBorrow);return poolCofig;} }4、redisService服務類
@Service public class RedisService {private Logger logger = LoggerFactory.getLogger(getClass());@Resource(name = "redisDevTemplate")private StringRedisTemplate redisTemplate;@Value("${global.env}")private String env;public int keys(String regEx) {regEx = env.concat("-").concat(regEx);try {return redisTemplate.keys(regEx).size();} catch (Exception e) {logger.error(e.getMessage(), e);}return -1;}public Object getValue(String key) {key = env.concat("-").concat(key);try {BoundValueOperations valueOperations = redisTemplate.boundValueOps(key);Object retValue = valueOperations.get();logger.info("get from redis {}:{}", key, retValue);return retValue;} catch (Exception e) {logger.error(e.getMessage(), e);}return null;}public void setValue(String key, Object value) {key = env.concat("-").concat(key);try {BoundValueOperations valueOperations = redisTemplate.boundValueOps(key);valueOperations.set(String.valueOf(value), 1, TimeUnit.DAYS);logger.info("set to redis {}:{}", key, value);} catch (Exception e) {logger.error(e.getMessage(), e);}}public void setValue(String key, Object value, int timeOut) {key = env.concat("-").concat(key);try {BoundValueOperations valueOperations = redisTemplate.boundValueOps(key);valueOperations.set(String.valueOf(value), timeOut, TimeUnit.SECONDS);logger.info("set to redis {}:{}", key, value);} catch (Exception e) {logger.error(e.getMessage(), e);}}/*** 自增1* @param key*/public long increment(String key) {//給Redis中key加前綴:dev-ApiAccessCntqibumaiche2018-07-17key = env.concat("-").concat(key); // return redisTemplate.opsForValue().increment(env.concat("-").concat(key), 1);logger.info("increment redis {}", key);//對應Redis的value的值加1return redisTemplate.opsForValue().increment(key, 1);}/*** 初始化0* @param key*/public void init(String key) {redisTemplate.opsForValue().set(env.concat("-").concat(key), String.valueOf(0));}public void delteKey(String key) {try {redisTemplate.delete(key);} catch (Exception e) {logger.error(e.getMessage(), e);}}/*** 入隊* @param key* @param value* @return*/public Long inQueue(String key, String value) {return redisTemplate.opsForList().rightPush(key, value);}/*** 出隊* @param key* @return*/public String outQueue(String key) {return redisTemplate.opsForList().leftPop(key);}/*** 棧/隊列長* @param key* @return*/public Long length(String key) {return redisTemplate.opsForList().size(key);}/*** hash添加* @param key* @param field* @param value*/public void hset(String key, String field, String value){try {HashOperations<String, String, String> vo = redisTemplate.opsForHash();vo.put(key,field,value);}catch (Exception e) {logger.error(e.getMessage(), e);}}/*** hash獲取* @param key* @param field* @return*/public String hget(String key, String field){String value = null;try {HashOperations<String, String, String> vo = redisTemplate.opsForHash();if(vo.hasKey(key,field)){value = vo.get(key,field);}}catch (Exception e) {logger.error(e.getMessage(), e);}return value;}/*** hash獲取所有* @param key* @return*/public Map<String,String> hgetall(String key){HashOperations<String, String, String> vo = redisTemplate.opsForHash();Map<String,String> map = new HashMap<>();for(String haskey:vo.keys(key)){String value = vo.get(key,haskey);map.put(haskey,value);}return map;} }以上可以注入多個redis數據源進行操作
?
原文:https://www.jianshu.com/p/c21e11739fec
?
總結
以上是生活随笔為你收集整理的springboot集成redis配置多数据源的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: maven常用依赖
- 下一篇: lombok @Builder注解的使