这个项目用到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的配置的更多相关文章

  1. Linux下Redis服务器安装配置

    说明:操作系统:CentOS1.安装编译工具yum install wget  make gcc gcc-c++ zlib-devel openssl openssl-devel pcre-devel ...

  2. CentOS下Redis服务器安装配置

    说明: 操作系统:CentOS 1.安装编译工具 yum install wget  make gcc gcc-c++ zlib-devel openssl openssl-devel pcre-de ...

  3. Windows下Redis安装配置和使用注意事项

    Windows下Redis安装配置和使用注意事项 一:下载 下载地址: https://github.com/microsoftarchive/redis/releases 文件介绍: 本文以3.2. ...

  4. Spring Boot Redis 集成配置(转)

    Spring Boot Redis 集成配置 .embody{ padding:10px 10px 10px; margin:0 -20px; border-bottom:solid 1px #ede ...

  5. spring集成redis——主从配置以及哨兵监控

    Redis主从模式配置: Redis的主从模式配置是非常简单的,首先我们需要有2个可运行的redis环境: master node : 192.168.56.101 8887 slave node: ...

  6. CentOS 6.6下Redis安装配置记录

    转载于:http://www.itxuexiwang.com/a/shujukujishu/redis/2016/0216/120.html?1455855209 在先前的文章中介绍过redis,以下 ...

  7. spring data redis jackson 配置,工具类

    spring data redis 序列化有jdk .jackson.string 等几种类型,自带的jackson不熟悉怎么使用,于是用string类型序列化,把对象先用工具类转成string,代码 ...

  8. 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 ...

  9. spring下redis使用资料

    参考资料地址: spring集成redis Spring缓存注解@Cacheable.@CacheEvict.@CachePut使用 redis常用命令 redis持久化(RDB与AOF) Redis ...

随机推荐

  1. PLsql链接oracle配置

    在Oracle的安装文件下查找tnsnames.ora文件 如果真的找不到路径,建议大家在Oracle安装位置全文搜索tnsnames.ora 配置格式 个人配置 下载并安装PL/SQL,成功安装后配 ...

  2. P1508 Likecloud-吃、吃、吃

    数字金字塔3条路 f[i][j]=max(max(f[i-1][j],f[i-1][j-1]),f[i-1][j+1])+a[i][j]; #include<bits/stdc++.h> ...

  3. linux下后台启动springboot项目

    linux下后台启动springboot项目 我们知道启动springboot的项目有三种方式: 运行主方法启动 使用命令 mvn spring-boot:run”在命令行启动该应用 运行“mvn p ...

  4. Scrapy爬取伯乐在线文章

    首先搭建虚拟环境,创建工程 scrapy startproject ArticleSpider cd ArticleSpider scrapy genspider jobbole blog.jobbo ...

  5. bzoj 2733 : [HNOI2012]永无乡 (线段树合并)

    Description 永无乡包含 n 座岛,编号从 1 到 n,每座岛都有自己的独一无二的重要度,按照重要度可 以将这 n 座岛排名,名次用 1 到 n 来表示.某些岛之间由巨大的桥连接,通过桥可以 ...

  6. Docker 私有仓库 Harbor registry 安全认证搭建 [Https]

    Harbor源码地址:https://github.com/vmware/harborHarbort特性:基于角色控制用户和仓库都是基于项目进行组织的, 而用户基于项目可以拥有不同的权限.基于镜像的复 ...

  7. zabbix监控概念

    监控:数据采集 --> 数据存储 -->  数据展示 报警:采集到的数据超出阈值 SNMP:Simple Network Management Protocol(只能实现数据采集) NMS ...

  8. ubuntu “无法获得锁 /var/lib/dpkg/lock -open”

    在ubuntu系统终端下,用apt-get install 安装软件的时候,如果在未完成下载的情况下将终端中断,此时 apt-get进程可能没有结束.结果,如果再次运行apt-get install ...

  9. linux deb系 rpm系 配置路由

    deb: 添加默认路由:route add default gw 8.46.192.1 添加网段路由:route add -net 8.46.0.0/19 gw 8.46.192.1 删除路由:把 a ...

  10. [JLOI2016/SHOI2016]侦察守卫(树形dp)

    小R和B神正在玩一款游戏.这款游戏的地图由N个点和N-1条无向边组成,每条无向边连接两个点,且地图是连通的.换句话说,游戏的地图是一棵有N个节点的树. 游戏中有一种道具叫做侦查守卫,当一名玩家在一个点 ...