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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章