1、pom.xml引入一下jar
<!-- spring-redis实现 -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.6.2.RELEASE</version>
</dependency>
<!-- redis客户端jar -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.0</version>
</dependency>
<!-- Ehcache实现,用于参考 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.0.0</version>
</dependency>
2、application-context.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:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
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/jee http://www.springframework.org/schema/jee/spring-jee-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">
<!-- 使用annotation 自动注册bean,并保证@Required,@Autowired的属性被注入 -->
<context:component-scan base-package="com.langcheng.**"/>
<!--<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> -->
<!-- redis配置 -->
<!-- redis连接池 -->
<bean id="jedisConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="10" />
<property name="maxTotal" value="105" />
<property name="maxWaitMillis" value="5000" />
<property name="testOnBorrow" value="true" />
</bean>
<!-- redis连接工厂 -->
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="127.0.0.1"></property>
<property name="port" value="6379"></property>
<property name="password" value=""></property>
<property name="poolConfig" ref="jedisConfig"></property>
</bean>
<!-- redis操作模板,这里采用尽量面向对象的模板 -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
<property name="connectionFactory" ref="connectionFactory" />
<!-- 如果不配置Serializer,那么存储的时候只能使用String,如果用对象类型存储,那么会提示错误 can't cast to String!!!
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
</property>
<property name="hashKeySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="hashValueSerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property> -->
</bean>
<!-- redis服务封装
<bean id="redisService" class="com.langcheng.redis.impl.RedisServiceImpl">
</bean> -->
</beans>
3、springmvc-Servlet.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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
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
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.2.xsd ">
<!-- 自动注册 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 扫描控制器 -->
<context:component-scan base-package="com.langcheng.controller" />
<!-- 扫描逻辑层
<context:component-scan base-package="com.langcheng.redis" />-->
<!--<context:component-scan base-package="com.langcheng.controller">
不再管理Controller 注解 因为它单独给mvc-servler.xml去管理
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>-->
<!-- <context:component-scan base-package="com.langcheng.aop.api"></context:component-scan>-->
<!-- jdk动态代理织入增强 @aspectJ切面的bean创建代理,织入切面 -->
<aop:aspectj-autoproxy expose-proxy="false" />
<tx:annotation-driven transaction-manager="transactionManager" order="2"/>
<!-- 静态资源访问 -->
<mvc:resources location="/resource/" mapping="/resource/**" />
<mvc:resources location="/intercity/" mapping="/intercity/**" />
<mvc:resources location="/ownersection/" mapping="/ownersection/**" />
<mvc:resources location="/" mapping="/**/*.html" />
<!--- StringHttpMessageConverter bean -->
<bean id="stringHttpMessageConverter"
class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8" index="0"></constructor-arg><!--
避免出现乱码 -->
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="stringHttpMessageConverter" />
</list>
</property>
</bean>
<!-- 视图解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass">
<value>org.springframework.web.servlet.view.JstlView</value>
</property>
<property name="prefix">
<value>/WEB-INF/page/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<!-- Session失效拦截
<mvc:interceptors> -->
<!-- 定义拦截器
<mvc:interceptor> -->
<!-- 匹配的是url路径, 如果不配置或/**,将拦截所有的Controller
<mvc:mapping path="/**" />
<mvc:exclude-mapping path="/**/fonts/*"/>
<mvc:exclude-mapping path="/**/*.css"/>
<mvc:exclude-mapping path="/**/*.js"/>
<mvc:exclude-mapping path="/**/**/*.js"/>
<mvc:exclude-mapping path="/**/*.png"/>
<mvc:exclude-mapping path="/**/*.gif"/>
<mvc:exclude-mapping path="/**/*.jpg"/>
<mvc:exclude-mapping path="/**/*.jpeg"/>
<mvc:exclude-mapping path="/**/*login*"/>
<mvc:exclude-mapping path="/**/*findUser*"/> -->
<!-- 不用拦截的路径
<bean class="com.langcheng.interceptor.LoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors> -->
<!-- ajaxSession失效过滤
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<list>
</list>
</property>
</bean> -->
<!-- 上传文件 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8" />
<!-- 最大内存大小 -->
<property name="maxInMemorySize" value="10240" />
<!-- 最大文件大小,-1为不限制大小 -->
<property name="maxUploadSize" value="-1" />
</bean>
</beans>
4、编写redis服务端用于测试
1.编写RedisService.java
package com.langcheng.redis.api;
import java.util.Set;
/**
* 封装redis 缓存服务器服务接口
* @author doop
*@version 1.0 测试版,联系使用
*/
public interface RedisService {
/**
* 通过key删除(字节)
* @param key
*/
public void del(byte [] key);
/**
* 通过key删除
* @param key
*/
public void del(String key);
/**
* 添加key value 并且设置存活时间(byte)
* @param key
* @param value
* @param liveTime
*/
public void set(byte [] key,byte [] value,int liveTime);
/**
* 添加key value 并且设置存活时间
* @param key
* @param value
* @param liveTime
*/
public void set(String key,String value,int liveTime);
/**
* 添加key value
* @param key
* @param value
*/
public void set(String key,String value);
/**添加key value (字节)(序列化)
* @param key
* @param value
*/
public void set(byte [] key,byte [] value);
/**
* 获取redis value (String)
* @param key
* @return
*/
public String get(String key);
/**
* 获取redis value (byte [] )(反序列化)
* @param key
* @return
*/
public byte[] get(byte [] key);
/**
* 通过正则匹配keys
* @param pattern
* @return
*/
public Set<String> keys(String pattern);
/**
* 检查key是否已经存在
* @param key
* @return
*/
public boolean exists(String key);
/**
* 清空redis 所有数据
* @return
*/
public String flushDB();
/**
* 查看redis里有多少数据
*/
public long dbSize();
/**
* 检查是否连接成功
* @return
*/
public String ping();
}
2.编写RedisServiceImpl
package com.langcheng.redis.impl;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import com.langcheng.redis.api.RedisService;
@Service
public class RedisServiceImpl implements RedisService{
//操作redis客户端
private static Jedis jedis;
@Autowired
private JedisConnectionFactory redisTemplate;
private RedisServiceImpl (){
}
@Override
public void del(byte[] key) {
// TODO Auto-generated method stub
this.getJedis().del(key);
}
@Override
public void del(String key) {
// TODO Auto-generated method stub
this.getJedis().del(key);
}
@Override
public void set(byte[] key, byte[] value, int liveTime) {
// TODO Auto-generated method stub
this.set(key, value);
this.getJedis().expire(key, liveTime);
}
@Override
public void set(String key, String value, int liveTime) {
// TODO Auto-generated method stub
this.set(key, value);
this.getJedis().expire(key, liveTime);
}
@Override
public void set(String key, String value) {
// TODO Auto-generated method stub
this.getJedis().set(key, value);
}
@Override
public void set(byte[] key, byte[] value) {
// TODO Auto-generated method stub
this.getJedis().set(key, value);
}
@Override
public String get(String key) {
// TODO Auto-generated method stub
String value = this.getJedis().get(key);
return value;
}
@Override
public byte[] get(byte[] key) {
// TODO Auto-generated method stub
return this.getJedis().get(key);
}
@Override
public Set<String> keys(String pattern) {
// TODO Auto-generated method stub
return this.getJedis().keys(pattern);
}
@Override
public boolean exists(String key) {
// TODO Auto-generated method stub
return this.getJedis().exists(key);
}
@Override
public String flushDB() {
// TODO Auto-generated method stub
return this.getJedis().flushDB();
}
@Override
public long dbSize() {
// TODO Auto-generated method stub
return this.getJedis().dbSize();
}
@Override
public String ping() {
// TODO Auto-generated method stub
return this.getJedis().ping();
}
/**
* 获取一个jedis 客户端
* @return
*/
private Jedis getJedis(){
if(jedis == null){
return redisTemplate.getShardInfo().createResource();
}
return jedis;
}
}
3.编写测试控制器
package com.langcheng.controller;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.langcheng.redis.api.RedisService;
@Controller
@RequestMapping(value = "/api")
public class RedisController {
@Autowired
private RedisService redisService;
@RequestMapping(value = "/test")
public void test1() {
String ping = redisService.ping();//测试是否连接成功,连接成功输出PONG
System.out.println(ping);
//首先,我们看下redis服务里是否有数据
long dbSizeStart = redisService.dbSize();
System.out.println(dbSizeStart);
redisService.set("username", "oyhk");//设值(查看了源代码,默认存活时间30分钟)
String username = redisService.get("username");//取值
System.out.println(username);
redisService.set("username1", "oyhk1", 1);//设值,并且设置数据的存活时间(这里以秒为单位)
String username1 = redisService.get("username1");
System.out.println(username1);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//我睡眠一会,再去取,这个时间超过了,他的存活时间
String liveUsername1 = redisService.get("username1");
System.out.println(liveUsername1);//输出null
//是否存在
boolean exist = redisService.exists("username");
System.out.println(exist);
//查看keys
Set<String> keys = redisService.keys("*");//这里查看所有的keys
System.out.println(keys);//只有username username1(已经清空了)
//删除
redisService.set("username2", "oyhk2");
String username2 = redisService.get("username2");
System.out.println(username2);
redisService.del("username2");
String username2_2 = redisService.get("username2");
System.out.println(username2_2);//如果为null,那么就是删除数据了
//dbsize
long dbSizeEnd = redisService.dbSize();
System.out.println(dbSizeEnd);
//清空reids所有数据
//redisService.flushDB();
}
}
进行测试输出结果: