第一步:添加需要的jar包
<!-- redis --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.1.0</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.0.3.RELEASE</version> </dependency>
第二步:配置文件
redis.properties
#redis setting
redis.ip=127.0.0.1
redis.port=6379
redis.maxActive=1000
redis.maxIdle=100
redis.maxWait=1000
redis.testOnBorrow=true
spring-redis.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxActive" value="${redis.maxActive}" /> <property name="maxIdle" value="${redis.maxIdle}" /> <property name="maxWait" value="${redis.maxWait}" /> <property name="testOnBorrow" value="${redis.testOnBorrow}" /> </bean> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="connectionFactory" /> <property name="keySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property> <property name="valueSerializer"> <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" /> </property> </bean> <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <property name ="hostName" value="${redis.ip}" /> <property name ="port" value="${redis.port}" /> <property name ="poolConfig" ref="poolConfig" /> </bean> <bean id="redisTemplateTool" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="targetClass" value="com.org.qin.common.utils.redis.RedisUtil" /> <property name="targetMethod" value="initRedis" /> <property name="arguments" ref="redisTemplate" /> </bean> </beans>
spring-bean.xml
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="order" value="1"/> <property name="ignoreUnresolvablePlaceholders" value="true"/> <property name="locations"> <list> <value>classpath:config/prop/redis.properties</value> </list> </property> </bean>
第三步:工具类
package com.org.qin.common.utils.redis; import java.io.Serializable; import java.util.concurrent.TimeUnit; import org.slf4j.LoggerFactory; import org.springframework.data.redis.core.RedisTemplate; import com.org.qin.common.constants.RedisConstants; public class RedisUtil { private static RedisTemplate<String, Serializable> redisTemplate; public static void initRedis(RedisTemplate<String, Serializable> redisTemplate) { RedisUtil.redisTemplate = redisTemplate; } public static void expire(String key, int seconds) { redisTemplate.expire(key, seconds, TimeUnit.SECONDS); } public static void delete(String key) { redisTemplate.delete(key); Object object = redisTemplate.opsForValue().get(key); System.out.println(object); } public static Object getObject(String key) { try{ return redisTemplate.opsForValue().get(key); } catch(Throwable e){ LoggerFactory.getLogger(RedisUtil.class).error("getObject", e); } return null; } public static void setObject(String key, Serializable object) { try{ redisTemplate.opsForValue().set(key, object, RedisConstants.DEFAULT_TIMEOUT_SECONDS, TimeUnit.SECONDS); } catch(Throwable e){ LoggerFactory.getLogger(RedisUtil.class).error("setObject", e); } } public static void setObject(String key, Serializable object, long timeout) { try{ redisTemplate.opsForValue().set(key, object, timeout, TimeUnit.SECONDS); } catch(Throwable e){ LoggerFactory.getLogger(RedisUtil.class).error("setObject", e); } } }
第四步:测试类
package com.org.qin.controller.cache; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.org.qin.common.utils.redis.RedisUtil; @Controller @RequestMapping("redis") public class RedisController { /** * 查询指定缓存 * * @param request * @return */ @RequestMapping("/getCache.htm") @ResponseBody public String getCache(HttpServletRequest request) { Map<String, Object> params = getRequestParams(request); return (String)RedisUtil.getObject((String)params.get("cacheKey")); } /** * 删除缓存 * * @param request * @return */ @RequestMapping("/deleteCache.htm") @ResponseBody public String deleteCache(HttpServletRequest request, HttpServletResponse response) { Map<String, Object> params = getRequestParams(request); RedisUtil.delete((String)params.get("cacheKey")); return "ok!"; } /** * 添加缓存 * * @param request * @return */ @RequestMapping("/setCache.htm") @ResponseBody public String setCache(HttpServletRequest request, HttpServletResponse response) { Map<String, Object> params = getRequestParams(request); RedisUtil.setObject((String)params.get("cacheKey"), (Serializable)params.get("cacheData")); return "ok!"; } /** * 功能描述: 获取请求参数 * * @param request * @return */ @SuppressWarnings("unchecked") public static Map<String, Object> getRequestParams(HttpServletRequest request) { Map<String, String[]> parameter = request.getParameterMap(); String[] obj; Set<Entry<String, String[]>> entries = parameter.entrySet(); Map<String, Object> params = new HashMap<String, Object>(entries.size()); for(Map.Entry<String, String[]> m : entries){ obj = m.getValue(); params.put(m.getKey(), (obj.length > 1) ? obj : obj[0]); } return params; } }
测试地址
http://localhost:12342/derella-web/redis/getCache.htm?cacheKey=test
http://localhost:12342/derella-web/redis/setCache.htm?cacheKey=test&cacheData=testdata
http://localhost:12342/derella-web/redis/deleteCache.htm?cacheKey=test