Redis(六)-- SpringMVC整合Redis
一、pom.xml
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 3 <modelVersion>4.0.0</modelVersion> 4 <groupId>com.xbq.demo</groupId> 5 <artifactId>SpringRedisDemo</artifactId> 6 <packaging>war</packaging> 7 <version>0.0.1-SNAPSHOT</version> 8 <name>SpringRedisDemo Maven Webapp</name> 9 <url>http://maven.apache.org</url> 10 11 <!-- Spring版本号 --> 12 <properties> 13 <org.springframework.version>4.2.3.RELEASE</org.springframework.version> 14 </properties> 15 16 <dependencies> 17 <dependency> 18 <groupId>javax.servlet</groupId> 19 <artifactId>servlet-api</artifactId> 20 <version>2.5</version> 21 </dependency> 22 <dependency> 23 <groupId>junit</groupId> 24 <artifactId>junit</artifactId> 25 <version>4.10</version> 26 <scope>test</scope> 27 </dependency> 28 <dependency> 29 <groupId>commons-logging</groupId> 30 <artifactId>commons-logging</artifactId> 31 <version>1.1.1</version> 32 </dependency> 33 <dependency> 34 <groupId>log4j</groupId> 35 <artifactId>log4j</artifactId> 36 <version>1.2.16</version> 37 </dependency> 38 <dependency> 39 <groupId>org.slf4j</groupId> 40 <artifactId>slf4j-api</artifactId> 41 <version>1.7.7</version> 42 </dependency> 43 <dependency> 44 <groupId>org.slf4j</groupId> 45 <artifactId>slf4j-log4j12</artifactId> 46 <version>1.7.7</version> 47 </dependency> 48 <dependency> 49 <groupId>redis.clients</groupId> 50 <artifactId>jedis</artifactId> 51 <version>2.9.0</version> 52 </dependency> 53 <dependency> 54 <groupId>org.apache.commons</groupId> 55 <artifactId>commons-pool2</artifactId> 56 <version>2.4.2</version> 57 </dependency> 58 <dependency> 59 <groupId>commons-fileupload</groupId> 60 <artifactId>commons-fileupload</artifactId> 61 <version>1.3.2</version> 62 </dependency> 63 <dependency> 64 <groupId>org.springframework.data</groupId> 65 <artifactId>spring-data-redis</artifactId> 66 <version>1.8.1.RELEASE</version> 67 </dependency> 68 <dependency> 69 <groupId>org.springframework</groupId> 70 <artifactId>spring-context</artifactId> 71 <version>${org.springframework.version}</version> 72 </dependency> 73 <dependency> 74 <groupId>org.springframework</groupId> 75 <artifactId>spring-core</artifactId> 76 <version>${org.springframework.version}</version> 77 </dependency> 78 <dependency> 79 <groupId>org.springframework</groupId> 80 <artifactId>spring-beans</artifactId> 81 <version>${org.springframework.version}</version> 82 </dependency> 83 <dependency> 84 <groupId>org.springframework</groupId> 85 <artifactId>spring-webmvc</artifactId> 86 <version>${org.springframework.version}</version> 87 </dependency> 88 <dependency> 89 <groupId>org.springframework</groupId> 90 <artifactId>spring-orm</artifactId> 91 <version>${org.springframework.version}</version> 92 </dependency> 93 <dependency> 94 <groupId>org.springframework</groupId> 95 <artifactId>spring-test</artifactId> 96 <version>${org.springframework.version}</version> 97 </dependency> 98 <dependency> 99 <groupId>org.springframework</groupId> 100 <artifactId>spring-aspects</artifactId> 101 <version>${org.springframework.version}</version> 102 </dependency> 103 <dependency> 104 <groupId>org.springframework</groupId> 105 <artifactId>spring-tx</artifactId> 106 <version>${org.springframework.version}</version> 107 </dependency> 108 </dependencies> 109 110 <build> 111 <finalName>SpringRedisDemo</finalName> 112 </build> 113 </project>
二、applicaltionContext.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:p="http://www.springframework.org/schema/p" 5 xmlns:aop="http://www.springframework.org/schema/aop" 6 xmlns:context="http://www.springframework.org/schema/context" 7 xmlns:jee="http://www.springframework.org/schema/jee" 8 xmlns:tx="http://www.springframework.org/schema/tx" 9 xmlns:cache="http://www.springframework.org/schema/cache" 10 xsi:schemaLocation=" 11 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 12 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 13 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd 14 http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd 15 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd "> 16 <!-- 自动扫描 --> 17 <context:component-scan base-package="com.xbq.demo.util"/> 18 <!-- 加载文件 --> 19 <context:property-placeholder location="classpath:redis.properties" /> 20 21 <!-- jedis 配置 --> 22 <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> 23 <property name="maxIdle" value="${redis.maxIdle}" /> 24 <property name="minIdle" value="${redis.minIdle}" /> 25 <property name="maxWaitMillis" value="${redis.maxWait}" /> 26 <property name="testOnBorrow" value="${redis.testOnBorrow}" /> 27 </bean> 28 <!-- redis服务器中心 --> 29 <bean id="connectionFactory" 30 class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> 31 <property name="poolConfig" ref="poolConfig" /> 32 <property name="port" value="${redis.port}" /> 33 <property name="hostName" value="${redis.host}" /> 34 <property name="password" value="${redis.pass}" /> 35 <property name="timeout" value="${redis.timeout}" /> 36 </bean> 37 <!-- redis操作模板,面向对象的模板 --> 38 <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate"> 39 <property name="connectionFactory" ref="connectionFactory" /> 40 <!-- 如果不配置Serializer,那么存储的时候只能使用String,如果用对象类型存储,那么会提示错误 --> 41 <property name="keySerializer"> 42 <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> 43 </property> 44 <property name="valueSerializer"> 45 <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" /> 46 </property> 47 </bean> 48 </beans>
三、redis.properties
1 redis.host=192.168.242.130 2 redis.port=6379 3 redis.pass=xbq123 4 redis.timeout=-1 5 6 redis.maxIdle=100 7 redis.minIdle=8 8 redis.maxWait=-1 9 redis.testOnBorrow=true
四、spring-mvc.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:p="http://www.springframework.org/schema/p" 5 xmlns:aop="http://www.springframework.org/schema/aop" 6 xmlns:context="http://www.springframework.org/schema/context" 7 xmlns:jee="http://www.springframework.org/schema/jee" 8 xmlns:tx="http://www.springframework.org/schema/tx" 9 xmlns:mvc="http://www.springframework.org/schema/mvc" 10 xsi:schemaLocation=" 11 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 12 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 13 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd 14 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd 15 http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd 16 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> 17 18 <!-- 视图解析器 --> 19 <bean id="viewResolver" 20 class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 21 <property name="prefix" value="/" /> 22 <property name="suffix" value=".jsp"></property> 23 </bean> 24 25 <bean id="multipartResolver" 26 class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 27 <property name="defaultEncoding" value="UTF-8"/> 28 <property name="maxUploadSize" value="10000000"/> 29 </bean> 30 31 <!-- 使用注解的包,包括子集 --> 32 <context:component-scan base-package="com.xbq.demo.controller"/> 33 </beans>
五、web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>SpringDemoTest</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- Spring配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath*:applicationContext.xml, </param-value> </context-param> <!-- 编码过滤器 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <async-supported>true</async-supported> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--spring监听器--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 防止spring内存溢出监听器--> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- 添加对springmvc的支持 --> <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*:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
六、封装一个操作hash基本数据类型的工具类
1 package com.xbq.demo.util; 2 3 import javax.annotation.Resource; 4 import org.springframework.data.redis.core.StringRedisTemplate; 5 import org.springframework.stereotype.Component; 6 7 /** 8 * 操作 hash 的基本操作 9 * @author xbq 10 */ 11 @Component("redisCache") 12 public class RedisCacheUtil { 13 14 @Resource 15 private StringRedisTemplate redisTemplate; 16 17 /** 18 * 向Hash中添加值 19 * @param key 可以对应数据库中的表名 20 * @param field 可以对应数据库表中的唯一索引 21 * @param value 存入redis中的值 22 */ 23 public void hset(String key, String field, String value) { 24 if(key == null || "".equals(key)){ 25 return ; 26 } 27 redisTemplate.opsForHash().put(key, field, value); 28 } 29 30 /** 31 * 从redis中取出值 32 * @param key 33 * @param field 34 * @return 35 */ 36 public String hget(String key, String field){ 37 if(key == null || "".equals(key)){ 38 return null; 39 } 40 return (String) redisTemplate.opsForHash().get(key, field); 41 } 42 43 /** 44 * 判断 是否存在 key 以及 hash key 45 * @param key 46 * @param field 47 * @return 48 */ 49 public boolean hexists(String key, String field){ 50 if(key == null || "".equals(key)){ 51 return false; 52 } 53 return redisTemplate.opsForHash().hasKey(key, field); 54 } 55 56 /** 57 * 查询 key中对应多少条数据 58 * @param key 59 * @return 60 */ 61 public long hsize(String key) { 62 if(key == null || "".equals(key)){ 63 return 0L; 64 } 65 return redisTemplate.opsForHash().size(key); 66 } 67 68 /** 69 * 删除 70 * @param key 71 * @param field 72 */ 73 public void hdel(String key, String field) { 74 if(key == null || "".equals(key)){ 75 return; 76 } 77 redisTemplate.opsForHash().delete(key, field); 78 } 79 }
七、测试类
1 package com.xbq.demo; 2 3 import org.junit.Before; 4 import org.junit.Test; 5 import org.springframework.context.support.ClassPathXmlApplicationContext; 6 import com.xbq.demo.util.RedisCacheUtil; 7 8 /** 9 * 测试 10 */ 11 public class RedisTest { 12 13 private RedisCacheUtil redisCache; 14 private static String key; 15 private static String field; 16 private static String value; 17 18 @Before 19 public void setUp() throws Exception { 20 ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); 21 context.start(); 22 redisCache = (RedisCacheUtil) context.getBean("redisCache"); 23 } 24 25 // 初始化 数据 26 static { 27 key = "tb_student"; 28 field = "stu_name"; 29 value = "一系列的关于student的信息!"; 30 } 31 32 // 测试增加数据 33 @Test 34 public void testHset() { 35 redisCache.hset(key, field, value); 36 System.out.println("数据保存成功!"); 37 } 38 39 // 测试查询数据 40 @Test 41 public void testHget(){ 42 String re = redisCache.hget(key, field); 43 System.out.println("得到的数据:" + re); 44 } 45 46 // 测试数据的数量 47 @Test 48 public void testHsize(){ 49 long size = redisCache.hsize(key); 50 System.out.println("数量为:" + size); 51 } 52 }
八、控制层 StudentController
1 package com.xbq.demo.controller; 2 3 import java.io.PrintWriter; 4 import javax.annotation.Resource; 5 import javax.servlet.http.HttpServletRequest; 6 import javax.servlet.http.HttpServletResponse; 7 import org.springframework.stereotype.Controller; 8 import org.springframework.web.bind.annotation.RequestMapping; 9 import com.xbq.demo.util.RedisCacheUtil; 10 11 /** 12 * 控制层 13 * @author xbq 14 */ 15 @Controller 16 @RequestMapping("/student/") 17 public class StudentController { 18 19 @Resource 20 private RedisCacheUtil redisCache; 21 22 // 查询数据 23 @RequestMapping("list") 24 public String list(HttpServletResponse response, HttpServletRequest request){ 25 String re = redisCache.hget("tb_student", "stu_id"); 26 try { 27 this.write(response, re); 28 } catch (Exception e) { 29 e.printStackTrace(); 30 } 31 return null; 32 } 33 34 /** 35 * 回写到页面上 36 * @param response 37 * @param o 38 * @throws Exception 39 */ 40 private void write(HttpServletResponse response, Object o) throws Exception{ 41 response.setContentType("text/html;charset=utf-8"); 42 PrintWriter out=response.getWriter(); 43 out.println(o.toString()); 44 out.flush(); 45 out.close(); 46 } 47 }
九、jsp页面
<body>
Hello World!
<a href="${pageContext.request.contextPath}/student/list.do">显示数据</a>
</body>
十、源码下载