spring整合redis配置
第一步:添加需要的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
spring整合redis配置的更多相关文章
- 网站性能优化小结和spring整合redis
现在越来越多的地方需要非关系型数据库了,最近网站优化,当然从页面到服务器做了相应的优化后,通过在线网站测试工具与之前没优化对比,发现有显著提升. 服务器优化目前主要优化tomcat,在tomcat目录 ...
- Spring整合Redis&JSON序列化&Spring/Web项目部署相关
几种JSON框架用法和效率对比: https://blog.csdn.net/sisyphus_z/article/details/53333925 https://blog.csdn.net/wei ...
- spring整合redis之hello
1.pom.xml文件 <dependencies> <!-- spring核心包 --> <dependency> <groupId>org.spri ...
- Spring整合Redis时报错:java.util.NoSuchElementException: Unable to validate object
我在Spring整合Redis时报错,我是犯了一个很低级的错误! 我设置了Redis的访问密码,在Spring的配置文件却没有配置密码这一项,配置上密码后,终于不报错了!
- Redis的安装以及spring整合Redis时出现Could not get a resource from the pool
Redis的下载与安装 在Linux上使用wget http://download.redis.io/releases/redis-5.0.0.tar.gz下载源码到指定位置 解压:tar -xvf ...
- Spring整合redis实现key过期事件监听
打开redis服务的配置文件 添加notify-keyspace-events Ex 如果是注释了,就取消注释 这个是在以下基础上进行添加的 Spring整合redis:https://www. ...
- Spring整合Redis,并配置Jedis连接池
目录 只言片语 创建redis连接池的配置文件 单机版 spring整合redis(使用JedisPool) 项目中使用示例 集群版 spring整合redis(使用JedisCluster) 项目中 ...
- (转)Spring整合Redis作为缓存
采用Redis作为Web系统的缓存.用Spring的Cache整合Redis. 一.关于redis的相关xml文件的写法 <?xml version="1.0" ...
- Spring整合redis,通过sentinel进行主从切换
实现功能描述: redis服务器进行Master-slaver-slaver-....主从配置,通过2台sentinel进行failOver故障转移,自动切换,采用该代码完全可以直接用于实际生产环境. ...
随机推荐
- python之gevent模块实现协程
Python通过yield提供了对协程的基本支持,但是不完全.而第三方的gevent为Python提供了比较完善的协程支持. gevent是第三方库,通过greenlet实现协程,其基本思想是: 当一 ...
- 我的JavaScript笔记--面向对象
单例模式 ??(基于对象,不能批量生产) var person = { name: "ywb", sayHi: funct ...
- Linq to Entity 多条件 OR查询
技术背景:框架MVC,linq to Entity 需要一定的lambda书写能力 问题:在简单的orm中完成一些简单的增删查改是通过where insert delete update 完成的,但是 ...
- 【BZOJ2055】80人环游世界 有上下界费用流
[BZOJ2055]80人环游世界 Description 想必大家都看过成龙大哥的<80天环游世界>,里面的紧张刺激的打斗场面一定给你留下了深刻的印象.现在就有这么 一个 ...
- group_concat 多对多关联, 统计分组数据, 结果拼接到一个字段
统计用户所有的角色, 结果: 1 张三 普通用户,管理员,XXX 2 李四 普通用户, XXX select ur.user_id,u.login_name,GROUP_CONCAT ...
- Android性能测试摘入(TestHome)
Android性能测试: 客户端性能测试 服务端性能测试 客户端性能测试: 1.ROM版本的性能测试(即手机的不同操作系统):关注功耗测试 2.应用的性能测 ...
- POJ 3037 Skiing(Dijkstra)
Skiing Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 4668 Accepted: 1242 Special ...
- Powershell Exchange Message Per Day Sent and Reveive
Powershell Exchange Message Per Day Sent and Reveive # Initialize some variables used for counting a ...
- JS给TR隔行换色,鼠标经过有动感
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DT ...
- caffe使用(2)
总体流程 https://blog.csdn.net/hjimce/article/details/48933813 https://zhuanlan.zhihu.com/p/24087905 1.编 ...