Redis 主要是用来做一些数据的缓存,用来处理一些临时数据,比如用户登录凭证,频繁访问但不会频繁更新的数据,
想使用 Redis 连接池。
首先需要在 pom.xml 中导入如下包:
org.springframework.data
spring-data-redis
1.8.4.RELEASE
redis.clients
jedis
2.9.0
然后需要创建一个配置文件 RedisConfig.java:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import redis.clients.jedis.JedisPoolConfig;
@Configuration
@EnableAutoConfiguration
public class RedisConfig {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.timeout}")
private int timeout;
@Value("${spring.redis.pool.max-idle}")
private int maxIdle;
@Value("${spring.redis.pool.max-wait}")
private long maxWaitMillis;
@Value("${spring.redis.password}")
private String password;
@Bean
@ConfigurationProperties(prefix="spring.redis")
public JedisPoolConfig getRedisConfig(){
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxIdle(maxIdle);
config.setMaxWaitMillis(maxWaitMillis);
return config;
}
@Bean
@ConfigurationProperties(prefix="spring.redis")
public JedisConnectionFactory getConnectionFactory(){
JedisConnectionFactory factory = new JedisConnectionFactory();
JedisPoolConfig config = getRedisConfig();
factory.setPoolConfig(config);
factory.setHostName(host);
factory.setPassword(password);
factory.setTimeout(timeout);
logger.info("JedisConnectionFactory bean init success.");
return factory;
}
@Bean
public RedisTemplate, ?> getRedisTemplate(){
return new StringRedisTemplate(getConnectionFactory());
}
}
在代码里面配置好RedisConfig后,需要在 application.properties 中配置 Redis 参数:
########################################################
###Redis (RedisConfiguration)
########################################################
spring.redis.database=0
spring.redis.port=6379
spring.redis.host=127.0.0.1
spring.redis.password=123
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=1
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=6000
spring.redis.timeout=5000
配置好之后,还需要封装一个操作类,用来简化我们的操作,首先定义接口:
/**
* Redis 操作封装类
*
* @author Demon-HY
*/
public interface RedisService {
boolean set(String key, String value);
String get(String key);
boolean expire(String key, long expire);
boolean setList(String key, List list);
List getList(String key, Class clz);
long lpush(String key, Object obj);
long rpush(String key, Object obj);
String lpop(String key);
boolean set(final String key, final String value, long expire);
Long incr(String key, long growthLength);
boolean del(String key);
}
接下来实现这个接口,在实现里面会用到我们之前配置的RedisConfig 中的 RedisTemplate:
@Service
public class RedisServiceImpl implements RedisService, Serializable {
@Autowired
private RedisTemplate redisTemplate;
@Override
public boolean set(final String key, final String value) {
return redisTemplate.execute((RedisCallback) connection -> {
RedisSerializer serializer = redisTemplate.getStringSerializer();
connection.set(serializer.serialize(key), serializer.serialize(value));
return true;
});
}
@Override
public boolean set(final String key, final String value, long expire) {
set(key, value);
return expire(key, expire);
}
@Override
public String get(final String key) {
try {
return redisTemplate.execute((RedisCallback) connection -> {
RedisSerializer serializer = redisTemplate.getStringSerializer();
byte[] value = connection.get(serializer.serialize(key));
return serializer.deserialize(value);
});
} catch (Exception e) {
return null;
}
}
@Override
public boolean expire(final String key, long expire) {
return redisTemplate.expire(key, expire, TimeUnit.SECONDS);
}
@Override
public boolean setList(String key, List list) {
String value = JsonUtil.toJson(list);
return set(key, value);
}
@Override
public List getList(String key, Class clz) {
String json = get(key);
if (json != null) {
return JsonUtil.toList(json, clz);
}
return null;
}
@Override
public long lpush(final String key, Object obj) {
final String value = JsonUtil.toJson(obj);
return redisTemplate.execute((RedisCallback) connection -> {
RedisSerializer serializer = redisTemplate.getStringSerializer();
return connection.lPush(serializer.serialize(key), serializer.serialize(value));
});
}
@Override
public long rpush(final String key, Object obj) {
final String value = JsonUtil.toJson(obj);
return redisTemplate.execute((RedisCallback) connection -> {
RedisSerializer serializer = redisTemplate.getStringSerializer();
return (long) connection.rPush(serializer.serialize(key), serializer.serialize(value));
});
}
@Override
public String lpop(final String key) {
return redisTemplate.execute((RedisCallback) connection -> {
RedisSerializer serializer = redisTemplate.getStringSerializer();
byte[] res = connection.lPop(serializer.serialize(key));
return serializer.deserialize(res);
});
}
@Override
public Long incr(String key, long growthLength) {
return redisTemplate.opsForValue().increment(key, growthLength);
}
@Override
public boolean del(String key) {
return redisTemplate.execute((RedisCallback) connection -> {
RedisSerializer serializer = redisTemplate.getStringSerializer();
connection.del(serializer.serialize(key));
return true;
});
}
}
现在准备工作都好了,可以直接使用了:
@RestController
public class TestHttpApi implements Serializable {
@Autowired
private RedisService redisService;
@RequestMapping("test")
public void testRedis() {
redisService.set("test", "123");
redisService.expire("test", 10);
}
}