一、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