配置准备
1.添加jar包依赖
<!-- redis客户端Jedis -->
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
2.加入Redis配置文件
spring-redis.xml
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- Redis连接池设置 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="${redis.pool.maxActive}" />
<!-- 最大空闲 -->
<property name="maxIdle" value="${redis.pool.maxIdle}" />
<property name="maxWaitMillis" value="${redis.pool.maxWait}" />
<!-- 连接时检查有效性 -->
<property name="testOnBorrow" value="${redis.pool.testOnBorrow}" />
</bean>
<!-- 创建Redis连接池,并做相关配置 -->
<bean id="jedisWritePool" class="com.henu.oto.cache.JedisPoolWriper"
depends-on="jedisPoolConfig">
<constructor-arg index="0" ref="jedisPoolConfig" />
<constructor-arg index="1" value="${redis.hostname}" />
<constructor-arg index="2" value="${redis.port}" type="int" />
</bean>
<!-- 创建Redis工具类,封装好Redis的连接已进行相关的操作 -->
<bean id="jedisUtil" class="com.henu.oto.cache.JedisUtil"
scope="singleton">
<property name="jedisPool">
<ref bean="jedisWritePool" />
</property>
</bean>
<bean id="jedisKeys" class="com.henu.oto.cache.JedisUtil$Keys"
scope="singleton">
<constructor-arg ref="jedisUtil"></constructor-arg>
</bean>
<bean id="jedisStrings" class="com.henu.oto.cache.JedisUtil$Strings"
scope="singleton">
<constructor-arg ref="jedisUtil"></constructor-arg>
</bean>
<bean id="jedisLists" class="com.henu.oto.cache.JedisUtil$Lists"
scope="singleton">
<constructor-arg ref="jedisUtil"></constructor-arg>
</bean>
<bean id="jedisSets" class="com.henu.oto.cache.JedisUtil$Sets"
scope="singleton">
<constructor-arg ref="jedisUtil"></constructor-arg>
</bean>
<bean id="jedisHash" class="com.henu.oto.cache.JedisUtil$Hash"
scope="singleton">
<constructor-arg ref="jedisUtil"></constructor-arg>
</bean>
</beans>
redis.properties
redis.hostname=127.0.0.1
redis.port=6379
redis.database=0
redis.pool.maxActive=100
redis.pool.maxIdle=20
redis.pool.maxWait=3000
redis.pool.testOnBorrow=true
注意添加到web.xml配置信息
注意添加到spring-dao配置信息
3.引入类文件
src\main\java\com\henu\oto\cache\JedisPoolWriper.java
package com.henu.oto.cache;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
* 强指定redis的JedisPool接口构造函数,这样才能在centos成功创建jedispool
*
* @author xiangze
*
*/
public class JedisPoolWriper {
// 创建Redis连接池对象
private JedisPool jedisPool;
public JedisPoolWriper(final JedisPoolConfig poolConfig, final String host,
final int port) {
try {
jedisPool = new JedisPool(poolConfig, host, port);
} catch (Exception e) {
e.printStackTrace();
}
}
public JedisPool getJedisPool() {
return jedisPool;
}
public void setJedisPool(JedisPool jedisPool) {
this.jedisPool = jedisPool;
}
}
src\main\java\com\henu\oto\cache\JedisUtil.java
点击查看完整代码
使用示例
修改server接口(便于删除该类型的redis key)
package com.henu.oto.service;
import com.henu.oto.entity.Area;
import java.util.List;
public interface AreaService {
// 添加一行即可
public static final String AREALISTKEY = "arealist";
List<Area> getAreaList();
}
修改serviceImpl实现类,实现redis读取
package com.henu.oto.service.impl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.henu.oto.cache.JedisUtil;
import com.henu.oto.dao.AreaDao;
import com.henu.oto.entity.Area;
import com.henu.oto.exceptions.AreaOperationException;
import com.henu.oto.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Service
public class AreaServiceImpl implements AreaService {
@Autowired
private AreaDao areaDao;
@Autowired
private JedisUtil.Keys jedisKeys;
@Autowired
private JedisUtil.Strings jedisStrings;
@Override
@Transactional
public List<Area> getAreaList() {
//有时候 key 需要根据业务需要而进行拼接使用,如拼接为:key_1、key_2等
String key = AREALISTKEY;
List<Area> areaList = null;
ObjectMapper mapper = new ObjectMapper();
if (!jedisKeys.exists(key)){
areaList = areaDao.queryArea();
String jsonString = null;
try {
jsonString = mapper.writeValueAsString(areaList);
} catch (JsonProcessingException e) {
e.printStackTrace();
throw new AreaOperationException(e.getMessage());
}
jedisStrings.set(key, jsonString);
}else {
String jsonString = jedisStrings.get(key);
JavaType javaType = mapper.getTypeFactory().constructParametricType(
ArrayList.class, Area.class
);
try {
areaList = mapper.readValue(jsonString, javaType);
} catch (IOException e) {
e.printStackTrace();
throw new AreaOperationException(e.getMessage());
}
}
return areaList;
}
}
(可选)创建对cache相关操作的service
package com.henu.oto.service;
public interface CacheService {
/**
* 依据key前缀删除匹配该模式下的所有k-v
* 如传入shopcategory,则以shopcategory打头的k-v都会被清空
* @param keyPreFix
*/
void removeFromCache(String keyPreFix);
}
(可选)创建对cache相关操作的serviceImpl
package com.henu.oto.service.impl;
import com.henu.oto.cache.JedisUtil;
import com.henu.oto.service.CacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Set;
@Service
public class CacheServiceImpl implements CacheService {
@Autowired
private JedisUtil.Keys jedisKeys;
@Override
public void removeFromCache(String keyPreFix) {
Set<String> keySet = jedisKeys.keys(keyPreFix + "*");
for (String key : keySet){
jedisKeys.del(key);
}
}
}
创建测试类进行测试(设置断点进行查看)
package com.henu.oto.service;
import com.henu.oto.BaseTest;
import com.henu.oto.entity.Area;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import static junit.framework.TestCase.assertEquals;
public class AreaServiceTest extends BaseTest {
@Autowired
private AreaService areaService;
@Autowired
private CacheService cacheService;
@Test
public void testGetAreaList(){
List<Area> areaList = areaService.getAreaList();
assertEquals("华源", areaList.get(0).getAreaName());
cacheService.removeFromCache(areaService.AREALISTKEY);
areaList = areaService.getAreaList();
}
}
注意添加测试基类的配置信息
添加redis配置文件位置
如果显示Redis连接失败可以尝试以下方法
①开放Redis端口6379
②关闭防火墙
③修改redis.conf文件,将 bind 127.0.0.1这一行注释掉,或是将127.0.0.1修改为0.0.0.0(redis默认只支持本地连接,修改为0.0.0.0时,这样就可以支持外机连接了)
④修改redis.conf文件,将protected-mode yes 改为no(解除保护模式,也是DENIED Redis is running in protected mode because protected mode is enabled问题的解决)
(以上方式没有顺序,对症下药)