Spring中使用Redis
这里只是简单讲述在Spring 中实现整合redis
目录
添加依赖
首先我们添加关于 reids 的依赖:
jedis(version 2.9.0)、spring-data-redis(version 1.8.1)
【注意版本号,如果版本号不对将会影响后面的的配置,比如ConnctionFactory再高版本就取消了。jedis 和 spring-data-redis不匹配将会报错】
就比如下面两个常见的错误
- Redis java.lang.NoClassDefFoundError: redis/clients/util/Pool
- Error creating bean with name 'jedisConnectionFactory' defined
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.8.1.RELEASE</version>
</dependency>
创建 redis.properties 属性文件
#reids ip
redis.hostname=192.168.*.*
#redis 端口
redis.port=6379
#最大空连接数
redis.maxTotal=10
#最大空闲数
redis.maxIdle=5
#最大等待时间
redis.maxWaitMillis=2000
#返回连接时,检测连接是否成功
redis.testOnBorrow=true
#超时时间
redis.timeout=2000
创建 sprin-redis.xml 配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:property-placeholder location="classpath:redis.properties"/>
<!--Redis数据源-->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<!--最大空闲数-->
<property name="maxIdle" value="${redis.maxIdle}"/>
<!--最大空连接数-->
<property name="maxTotal" value="${redis.maxTotal}"/>
<!--最大等待时间-->
<property name="maxWaitMillis" value="${redis.maxWaitMillis}"/>
<!--返回连接时,检测连接是否成功-->
<property name="testOnBorrow" value="${redis.testOnBorrow}"/>
</bean>
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<!--主机名-->
<property name="hostName" value="${redis.hostname}"/>
<!--端口-->
<property name="port" value="${redis.port}"/>
<!--超时时间-->
<property name="timeout" value="${redis.timeout}"/>
<!--连接池配置-->
<property name="poolConfig" ref="poolConfig"/>
<!--是否使用连接池-->
<property name="usePool" value="true"/>
</bean>
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory"/>
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="hashKeySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="hashValueSerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<!--开启事务-->
<property name="enableTransactionSupport" value="true"/>
</bean>
</beans>
其中 RedisTemplate 中设置了jedis连接工厂和对键值的序列化操作。
下面我们写一个 RedisServiceImpl去封装操作
RedisServiceImpl
@Service
public class RedisServiceImpl {
/**控制台日志输出*/
private Logger logger = LoggerFactory.getLogger(this.getClass());
/**RedisTemplate*/
private final RedisTemplate<String,Object> redisTemplate;
public RedisServiceImpl(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
/**
* 设置键值对的生存时间(TTL)
* @param key 键
* @param time 生存时间
* @return 设置成功与否
*/
public boolean expire(String key,long time){
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
}catch (Exception e){
logger.error("[Redis Error] "+e);
return false;
}
}
/**
* 获取键值对的生存时间
* @param key 键
* @return 生存时间
*/
public long getExpire(String key){
return redisTemplate.getExpire(key,TimeUnit.SECONDS);
}
/**
* 判断是否有某个键
* @param key 键
* @return 布尔值
*/
public boolean hasKey(String key){
try{
return redisTemplate.hasKey(key);
}catch (Exception e){
logger.error("[Redis Error] "+e);
return false;
}
}
/**
* 删除某些键值对
* @param key 键。。
*/
public void delete(String... key){
if (null != key&& key.length>0){
if (key.length == 1){
redisTemplate.delete(key[0]);
}else{
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
/**
* 获取某一个键值
* @param key 键
* @return 键值
*/
public Object get(String key){
return key == null?null:redisTemplate.opsForValue().get(key);
}
/**
* 设置键值对
* @param key 键
* @param value 值
* @return 布尔值:是否设置成功
*/
public boolean set(String key,Object value){
try{
redisTemplate.opsForValue().set(key,value);
return true;
}catch (Exception e){
logger.error("[Redis Error] "+e);
return false;
}
}
/**
* 设置键值对以及生存时间(TTL)
* @param key 键
* @param value 值
* @param time 生存时间
* @return 布尔值:是否设置成功
*/
public boolean set(String key,Object value,long time){
try {
if (time>0){
redisTemplate.opsForValue().set(key,value,time,TimeUnit.SECONDS);
}else{
set(key,value);
}
return true;
}catch (Exception e){
logger.error("[Redis Error] "+e);
return false;
}
}
/**
* 给键值增加
* @param key 键
* @param data 增加值
* @return long
*/
public long increment(String key,long data){
if (data<0){
throw new RuntimeException("增加得因子必须大于0");
}
return redisTemplate.opsForValue().increment(key,-data);
}
}
在 Controller 中测试
@Controller
public class HelloController {
@Resource
RedisServiceImpl redisService;
@RequestMapping("/test")
@ResponseBody
public Map<String,String> hello() throws UnsupportedEncodingException {
Jedis jedis = new Jedis();
Map<String,String> map = new HashMap<>();
String test = jedis.get("test");
String srt = jedis.get("srt");
map.put("test",test);
map.put("srt",srt);
map.put("redisTemplate", (String) redisService.get("test"));
map.put("msg","你好");
return map;
}
}
打开浏览器,可以看见输出