Spring下redis的配置
这个项目用到redis,所以学了一下怎样在Spring框架下配置redis。
1、首先是在web.xml中添加Spring的配置文件。
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name>common design</display-name> <context-param>
<param-name>webAppRootKey</param-name>
<param-value>webapp.root</param-value>
</context-param> <!-- 添加Spring mybatis的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml,classpath*:mybatis-config.xml</param-value>
</context-param> <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
</servlet> <servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping> </web-app>
2、然后是redis的配置文件(redis-config.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" 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/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"
default-autowire="byName" default-lazy-init="true"> <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxWaitMillis" value="${redis.maxWait}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean>
<!-- redis服务器中心 -->
<bean id="connectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="poolConfig" ref="poolConfig" />
<property name="port" value="${redis.port}" />
<property name="hostName" value="${redis.host}" />
<property name="password" value="${redis.password}" />
<property name="timeout" value="${redis.timeout}"></property>
</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="redisUtil" class="com.zkxl.fep.redis.RedisUtil">
<property name="redisTemplate" ref="redisTemplate" />
</bean> </beans>
在Spring的配置文件中引用redis的配置文件
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" 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/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"
default-autowire="byName" default-lazy-init="true"> <context:annotation-config/>
<context:component-scan base-package="com.test.fep" /> <!-- 增加redis的properties文件 -->
<context:property-placeholder location="classpath*:jdbc.properties,classpath*:redis.properties" /> <import resource="datasource.xml"/>
<!-- 导入redis的配置文件 -->
<import resource="redis-config.xml"/> </beans>
3、新建redis.properties,里面包含redis连接需要的配置信息
#redis setting
redis.host=127.0.0.1
redis.port=6379
redis.password=123456
redis.maxIdle=100
redis.maxActive=300
redis.maxWait=1000
redis.testOnBorrow=true
redis.timeout=100000 fep.local.cache.capacity =10000
一定要注意,每行后面千万不要有空格,我就是因为这个问题卡了一两个小时= =
4、编写RedisUtil.java,里面放有redis的增删改查操作。
package com.test.fep.redis; import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations; public class RedisUtil { private RedisTemplate<Serializable, Object> redisTemplate; /**
* 批量删除对应的value
*
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
} /**
* 批量删除key
*
* @param pattern
*/
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0)
redisTemplate.delete(keys);
} /**
* 删除对应的value
*
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
} /**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
} /**
* 读取缓存
*
* @param key
* @return
*/
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
} /**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
logger.error("set cache error", e);
}
return result;
} /**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
logger.error("set cache error", e);
}
return result;
} public long increment(final String key , long delta){
return redisTemplate.opsForValue().increment(key, delta);
} public void setRedisTemplate(RedisTemplate<Serializable, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
}
5、在功能代码中调用RedisUtil类中的方法,
package com.test.fep.service.impl; import java.math.BigDecimal;
import java.util.Date;
import java.util.List; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.test.fep.domain.SysAppLoginToken;
import com.test.fep.mapper.SysAppLoginTokenMapper;
import com.test.fep.redis.RedisUtil;
import com.test.fep.service.AuthService; import net.sf.json.JSONObject; @Service("authService")
public class AuthServiceImpl implements AuthService{
@Autowired
private SysAppLoginTokenMapper sysAppLoginTokenMapper ; @Autowired
private RedisUtil redisUtil; //记得注入 @Override
public SysAppLoginToken verification(String tokenId) {
SysAppLoginToken token = null;
if (redisUtil.exists(tokenId)) {
token = (SysAppLoginToken) redisUtil.get(tokenId); //从缓存中查找token
}else{
token = sysAppLoginTokenMapper.selectByPrimaryKey(tokenId) ;
redisUtil.set(tokenId, token); //将token写入缓存
} return null;
}
}
好了,到这里就在一个项目中完整地使用了redis。
还需要注意的一点是,所有保存在Redis中的接口都必须要实现Serializable接口
Spring下redis的配置的更多相关文章
- Linux下Redis服务器安装配置
说明:操作系统:CentOS1.安装编译工具yum install wget make gcc gcc-c++ zlib-devel openssl openssl-devel pcre-devel ...
- CentOS下Redis服务器安装配置
说明: 操作系统:CentOS 1.安装编译工具 yum install wget make gcc gcc-c++ zlib-devel openssl openssl-devel pcre-de ...
- Windows下Redis安装配置和使用注意事项
Windows下Redis安装配置和使用注意事项 一:下载 下载地址: https://github.com/microsoftarchive/redis/releases 文件介绍: 本文以3.2. ...
- Spring Boot Redis 集成配置(转)
Spring Boot Redis 集成配置 .embody{ padding:10px 10px 10px; margin:0 -20px; border-bottom:solid 1px #ede ...
- spring集成redis——主从配置以及哨兵监控
Redis主从模式配置: Redis的主从模式配置是非常简单的,首先我们需要有2个可运行的redis环境: master node : 192.168.56.101 8887 slave node: ...
- CentOS 6.6下Redis安装配置记录
转载于:http://www.itxuexiwang.com/a/shujukujishu/redis/2016/0216/120.html?1455855209 在先前的文章中介绍过redis,以下 ...
- spring data redis jackson 配置,工具类
spring data redis 序列化有jdk .jackson.string 等几种类型,自带的jackson不熟悉怎么使用,于是用string类型序列化,把对象先用工具类转成string,代码 ...
- spring data jpa和spring data redis同时配置时,出现Multiple Spring Data modules found, entering strict repository configuration mode错误
问题说明 data jpa和data redis同时配置时,出现Spring modules spring Spring Data Release Train <dependencyManage ...
- spring下redis使用资料
参考资料地址: spring集成redis Spring缓存注解@Cacheable.@CacheEvict.@CachePut使用 redis常用命令 redis持久化(RDB与AOF) Redis ...
随机推荐
- codeforces703B
Mishka and trip CodeForces - 703B 小米什卡是一个伟大的旅行者,她访问了许多国家.在这次考虑去哪里旅行之后,她选择了XXX--这个美丽,但鲜为人知的北方国家. 以下是关 ...
- 11/5/2018模拟 Problem C
题面 题解 我有特殊的哈希技巧 以到下一个相同字符的距离为值哈希, 如果不存在或在串外, 就是 \(|T| + 1\). 加入一个新字符 \(S_i\) 时, 同时修改它上一次出现时的值, 由 \(| ...
- linux 目录分类与文件操作
/ 虚拟根目录 一般不会在这里存储文件 /bin 二进制目录,存放需要GNU用户级的工具 /boot 启动目录,存放启动文件 /dev 设备目录,linux在这里创建设备节点 /etc 系统配置文件目 ...
- P2123 皇后游戏
题目背景 还记得 NOIP 2012 提高组 Day1 的国王游戏吗?时光飞逝,光阴荏苒,两年 过去了.国王游戏早已过时,如今已被皇后游戏取代,请你来解决类似于国王游 戏的另一个问题. 题目描述 皇后 ...
- Java自定义线程池-记录每个线程执行耗时
ThreadPoolExecutor是可扩展的,其提供了几个可在子类化中改写的方法,如下: protected void beforeExecute(Thread t, Runnable r) { } ...
- PHP——emjoin表情存入数据库
前言 还有一种解决的方法是更改数据库,这里就不写了,这里直接对emoji进行转码 代码 mb_strlen() | strlen() | rawurlencode() | rawurldecode() ...
- POJ 3580-SuperMemo-splay树
很完整的splay操作.做了这题就可以当板子用了. #include <cstdio> #include <algorithm> #include <cstring> ...
- 【BZOJ5288】[HNOI2018]游戏(拓扑排序)
[BZOJ5288][HNOI2018]游戏(拓扑排序) 题面 BZOJ 洛谷 题解 去年省选的时候这题给我乱搞整过去整过去了,也是虐心了.... 所以当然是来讲正儿八经的正确做法啦. 很明显,我们需 ...
- 「SCOI2014」方伯伯的商场之旅 解题报告
「SCOI2014」方伯伯的商场之旅 我一开始的想法会被两个相同的集合位置去重给搞死,不过应该还是可以写的,讨论起来老麻烦. 可以先钦定在\(1\)号点集合,然后往后调整一部分. 具体一点,通过前缀和 ...
- luogu3250 网络 (整体二分+树上差分+树状数组)
首先整体二分,问题变成是否存在经过一个点的满足条件的路径 那么我对于每个路径(a,b,lca),在树状数组的dfn[a]++,dfn[b]++,dfn[lca]--,dfn[fa[lca]--] 然后 ...