Redis(七)-- SpringMVC整合Redis集群

1.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.redis</groupId>
  5   <artifactId>SpringRedisCluster</artifactId>
  6   <packaging>war</packaging>
  7   <version>0.0.1-SNAPSHOT</version>
  8   <name>SpringRedisCluster Maven Webapp</name>
  9   <url>http://maven.apache.org</url>
 10   
 11   <properties>
 12      <org.springframework.version>4.2.2.RELEASE</org.springframework.version>
 13   </properties>
 14   
 15   <dependencies>
 16     <dependency>
 17       <groupId>junit</groupId>
 18       <artifactId>junit</artifactId>
 19       <version>4.10</version>
 20       <scope>test</scope>
 21     </dependency>
 22     
 23     <dependency>
 24         <groupId>javax.servlet</groupId>
 25         <artifactId>servlet-api</artifactId>
 26         <version>2.5</version>
 27     </dependency>
 28     <!-- 日志处理 -->
 29     <dependency>
 30         <groupId>commons-logging</groupId>
 31         <artifactId>commons-logging</artifactId>
 32         <version>1.1.1</version>
 33     </dependency>
 34     <dependency>
 35         <groupId>log4j</groupId>
 36         <artifactId>log4j</artifactId>
 37         <version>1.2.16</version>
 38     </dependency>
 39     <dependency>
 40         <groupId>org.slf4j</groupId>
 41         <artifactId>slf4j-api</artifactId>
 42         <version>1.7.7</version>
 43     </dependency>
 44     <!-- redis依赖 -->
 45     <dependency>
 46         <groupId>redis.clients</groupId>
 47         <artifactId>jedis</artifactId>
 48         <version>2.7.3</version>
 49     </dependency>
 50     <!-- spring依赖 -->
 51     <dependency>
 52         <groupId>org.springframework</groupId>
 53         <artifactId>spring-context</artifactId>
 54         <version>${org.springframework.version}</version>
 55     </dependency>
 56     <dependency>
 57         <groupId>org.springframework</groupId>
 58         <artifactId>spring-core</artifactId>
 59         <version>${org.springframework.version}</version>
 60     </dependency>
 61     <dependency>
 62         <groupId>org.springframework</groupId>
 63         <artifactId>spring-beans</artifactId>
 64         <version>${org.springframework.version}</version>
 65     </dependency>
 66     <dependency>
 67         <groupId>org.springframework</groupId>
 68         <artifactId>spring-webmvc</artifactId>
 69         <version>${org.springframework.version}</version>
 70     </dependency>
 71     <dependency>
 72         <groupId>org.springframework</groupId>
 73         <artifactId>spring-orm</artifactId>
 74         <version>${org.springframework.version}</version>
 75     </dependency>
 76     <dependency>
 77         <groupId>org.springframework</groupId>
 78         <artifactId>spring-test</artifactId>
 79         <version>${org.springframework.version}</version>
 80     </dependency>
 81     <dependency>
 82         <groupId>org.springframework</groupId>
 83         <artifactId>spring-aspects</artifactId>
 84         <version>${org.springframework.version}</version>
 85     </dependency>
 86     <dependency>
 87         <groupId>org.springframework</groupId>
 88         <artifactId>spring-tx</artifactId>
 89         <version>${org.springframework.version}</version>
 90     </dependency>
 91     <!-- jacksoon依赖 -->
 92     <dependency>
 93         <groupId>com.fasterxml.jackson.core</groupId>
 94         <artifactId>jackson-core</artifactId>
 95         <version>2.0.0</version>
 96     </dependency>
 97     <dependency>
 98         <groupId>org.codehaus.jackson</groupId>
 99         <artifactId>jackson-mapper-asl</artifactId>
100         <version>1.8.7</version>
101     </dependency>
102     <dependency>
103         <groupId>net.sf.json-lib</groupId>
104         <artifactId>json-lib</artifactId>
105         <version>2.1</version>
106         <classifier>jdk15</classifier>
107     </dependency>
108   </dependencies>
109   
110   <build>
111     <finalName>SpringRedisCluster</finalName>
112   </build>
113 </project>
View Code

2.web.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 3     xmlns="http://java.sun.com/xml/ns/javaee" 
 4     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
 5     id="WebApp_ID" version="3.0">
 6 
 7     <display-name>SpringRedisCluster</display-name>
 8     <welcome-file-list>
 9       <welcome-file>index.jsp</welcome-file>
10     </welcome-file-list>
11   
12       <!--配置字符过滤器-->
13       <filter>
14         <filter-name>encodingFilter</filter-name>
15         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
16         <async-supported>true</async-supported>
17         <init-param>
18             <param-name>encoding</param-name>
19             <param-value>UTF-8</param-value>
20         </init-param>
21     </filter>
22     <filter-mapping>
23         <filter-name>encodingFilter</filter-name>
24         <url-pattern>/*</url-pattern>
25     </filter-mapping>
26     
27     <!-- Spring监听器 -->
28     <listener>
29         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
30     </listener>
31     <!-- 防止Spring内存溢出监听器 -->  
32     <listener>  
33         <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>  
34     </listener>  
35     <context-param>
36         <param-name>contextConfigLocation</param-name>
37         <param-value>classpath:applicationContext.xml</param-value>
38     </context-param>
39     
40     <!-- 添加对springmvc的支持 -->
41     <servlet>
42         <servlet-name>springMVC</servlet-name>
43         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
44         <init-param>
45             <param-name>contextConfigLocation</param-name>
46             <param-value>classpath:spring-mvc.xml</param-value>
47         </init-param>
48         <load-on-startup>1</load-on-startup>
49         <async-supported>true</async-supported>
50     </servlet>
51     <servlet-mapping>
52         <servlet-name>springMVC</servlet-name>
53         <url-pattern>*.do</url-pattern>
54     </servlet-mapping>
55     <servlet-mapping>
56         <servlet-name>springMVC</servlet-name>
57         <url-pattern>*.html</url-pattern>
58     </servlet-mapping>
59 </web-app>
View Code

3.spring配置,applicationContext.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:aop="http://www.springframework.org/schema/aop"
 5        xmlns:context="http://www.springframework.org/schema/context"
 6        xmlns:jdbc="http://www.springframework.org/schema/jdbc"
 7        xmlns:tx="http://www.springframework.org/schema/tx"
 8        xmlns:jpa="http://www.springframework.org/schema/data/jpa"
 9        xmlns:util="http://www.springframework.org/schema/util"
10        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
11         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
12         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
13         http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.2.xsd
14         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
15         http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"
16        default-lazy-init="true">
17 
18     <description>Spring公共配置</description>
19     
20     <!-- 使用annotation 自动注册bean,并检查@Required,@Autowired的属性已被注入 -->
21     <context:component-scan base-package="com.xbq"/>
22     <context:annotation-config />
23     <!-- redis配置 -->
24     <import resource="classpath:redis.xml"/>
25 </beans>
View Code

4.redis配置,redis.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" xmlns:p="http://www.springframework.org/schema/p"  
 4     xmlns:context="http://www.springframework.org/schema/context"  
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans  
 6     http://www.springframework.org/schema/beans/spring-beans-4.2.xsd  
 7     http://www.springframework.org/schema/context  
 8     http://www.springframework.org/schema/context/spring-context-4.2.xsd">  
 9     
10     <!-- 连接池配置 -->    
11     <bean name="genericObjectPoolConfig" class="org.apache.commons.pool2.impl.GenericObjectPoolConfig" >  
12         <property name="maxWaitMillis" value="-1" />  
13         <property name="maxTotal" value="1000" />  
14         <property name="minIdle" value="8" />  
15         <property name="maxIdle" value="100" />  
16     </bean>  
17   
18     <bean id="jedisCluster" class="com.xbq.redis.JedisClusterFactory">  
19         <property name="addressConfig">  
20             <value>classpath:connect-redis.properties</value>  
21         </property>  
22         <property name="addressKeyPrefix" value="address" />   <!--  属性文件里  key的前缀 -->
23         <property name="timeout" value="300000" />  
24          <!--代表集群有几台redis-->
25         <property name="maxRedirections" value="6" />  
26         <property name="genericObjectPoolConfig" ref="genericObjectPoolConfig" />
27     </bean> 
28 </beans>  

5.redis集群的地址配置,connect-redis.properties,这里可以随便配置几个地址都可以。

address1=192.168.80.128:1000
address2=192.168.80.128:1001
address3=192.168.80.128:2000
address4=192.168.80.128:2001
address5=192.168.80.128:3000
address6=192.168.80.128:3001

6.springMVC配置,spring-mvc.xml

 1 <beans xmlns="http://www.springframework.org/schema/beans"
 2     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
 3     xmlns:context="http://www.springframework.org/schema/context"
 4     xmlns:task="http://www.springframework.org/schema/task" 
 5     xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
 6     xsi:schemaLocation="
 7         http://www.springframework.org/schema/util
 8         http://www.springframework.org/schema/util/spring-util-4.2.xsd
 9         http://www.springframework.org/schema/beans 
10         http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
11         http://www.springframework.org/schema/context 
12         http://www.springframework.org/schema/context/spring-context-4.2.xsd
13         http://www.springframework.org/schema/mvc
14         http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
15         http://www.springframework.org/schema/task 
16         http://www.springframework.org/schema/task/spring-task-4.2.xsd">
17 
18     <!-- 解决springMVC响应数据乱码   text/plain就是响应的时候原样返回数据 -->
19     <mvc:annotation-driven>
20         <mvc:message-converters register-defaults="true">
21         <bean class="org.springframework.http.converter.StringHttpMessageConverter">
22           <property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
23         </bean>
24        </mvc:message-converters>
25    </mvc:annotation-driven>
26 
27     <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->  
28     <context:component-scan base-package="com.*.controller" />
29 
30     <!-- 视图解析器 -->
31     <bean id="viewResolver"
32         class="org.springframework.web.servlet.view.InternalResourceViewResolver">
33         <property name="prefix" value="/" />
34         <property name="suffix" value=".jsp"></property>
35     </bean>
36 
37     <!-- 控制器异常处理 -->
38     <bean id="exceptionResolver"
39         class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
40         <property name="exceptionMappings">
41             <props>
42                 <prop key="java.lang.Exception">
43                     error
44                 </prop>
45             </props>
46         </property>
47     </bean>
48 </beans>
View Code

7.redis集群工厂配置,JedisClusterFactory.java

  1 package com.xbq.redis;
  2 
  3 import java.util.HashSet;
  4 import java.util.Properties;
  5 import java.util.Set;
  6 import java.util.regex.Pattern;
  7 
  8 import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
  9 import org.springframework.beans.factory.FactoryBean;
 10 import org.springframework.beans.factory.InitializingBean;
 11 import org.springframework.core.io.Resource;
 12 
 13 import redis.clients.jedis.HostAndPort;
 14 import redis.clients.jedis.JedisCluster;
 15 
 16 /**
 17  * Jedis集群工厂
 18  * @author xbq
 19  * @Date 2017-05-14
 20  */
 21 public class JedisClusterFactory implements InitializingBean,FactoryBean<JedisCluster>{
 22 
 23     private Resource addressConfig;
 24     
 25     // 下面变量 对应spring redis配置文件中的 property的name
 26     private JedisCluster jedisCluster;
 27     private String addressKeyPrefix;
 28     private Integer timeout;
 29     private Integer maxRedirections;
 30     private GenericObjectPoolConfig genericObjectPoolConfig;
 31     
 32     // 正则表达式 匹配 ip和port
 33     private Pattern p = Pattern.compile("^.+[:]\d{1,5}\s*$");
 34     
 35     /**
 36      * 实现 InitializingBean 的接口,初始化的 得到 jedisCluster
 37      */
 38     public void afterPropertiesSet() throws Exception {
 39         Set<HostAndPort> jedisClusterNode= this.parseHostAndPort();
 40         jedisCluster = new JedisCluster(jedisClusterNode, timeout, maxRedirections, genericObjectPoolConfig);
 41     }
 42 
 43     /**
 44      * 实现 FactoryBean 的接口
 45      * 获取 jedisCluster对象
 46      */
 47     public JedisCluster getObject() throws Exception {
 48         return jedisCluster;
 49     }
 50 
 51     /**
 52      * 实现 FactoryBean 的接口
 53      * 获取 jedisCluster的类型
 54      */
 55     public Class<? extends JedisCluster> getObjectType() {
 56         return (jedisCluster != null ? this.jedisCluster.getClass() : JedisCluster.class);
 57     }
 58 
 59     /**
 60      * 实现 FactoryBean 的接口
 61      */
 62     public boolean isSingleton() {
 63         return true;
 64     }
 65     
 66     /**
 67      * 解析Jedis配置文件,看是否满足 IP和端口
 68      * @return
 69      */
 70     private Set<HostAndPort> parseHostAndPort() throws Exception{
 71         Set<HostAndPort> hostAndPorts = new HashSet<HostAndPort>();
 72         try {
 73             Properties properties = new Properties();
 74             properties.load(this.addressConfig.getInputStream());
 75             
 76             for(Object key : properties.keySet()){
 77                 // 如果key不是以 addressKeyPrefix的值 开头,则continue
 78                 if(!((String)key).startsWith(addressKeyPrefix)){
 79                     continue;
 80                 }
 81                 // 根据 key从properties中取出值
 82                 String valus = (String) properties.get(key);
 83                 // 判断取出的value是否是ip和port
 84                 boolean isIPProt = p.matcher(valus).matches();
 85                 if(!isIPProt){
 86                     throw new IllegalArgumentException("ip和port不合法!");
 87                 }
 88                 String[] ipAndPort = valus.split(":");
 89                 HostAndPort hostAndPort = new HostAndPort(ipAndPort[0], Integer.parseInt(ipAndPort[1]));
 90                 hostAndPorts.add(hostAndPort);
 91             }
 92         } catch (Exception e) {
 93             throw new Exception("解析 jedis 配置文件失败!");
 94         }
 95         return hostAndPorts;
 96     }
 97 
 98     // set方法
 99     public void setJedisCluster(JedisCluster jedisCluster) {
100         this.jedisCluster = jedisCluster;
101     }
102     public void setAddressKeyPrefix(String addressKeyPrefix) {
103         this.addressKeyPrefix = addressKeyPrefix;
104     }
105     public void setTimeout(Integer timeout) {
106         this.timeout = timeout;
107     }
108     public void setMaxRedirections(Integer maxRedirections) {
109         this.maxRedirections = maxRedirections;
110     }
111     public void setGenericObjectPoolConfig(GenericObjectPoolConfig genericObjectPoolConfig) {
112         this.genericObjectPoolConfig = genericObjectPoolConfig;
113     }
114     public void setAddressConfig(Resource addressConfig) {
115         this.addressConfig = addressConfig;
116     }
117 }

8.控制层,RedisController.java

 1 package com.xbq.controller;
 2 
 3 import javax.annotation.Resource;
 4 import org.springframework.stereotype.Controller;
 5 import org.springframework.web.bind.annotation.RequestMapping;
 6 import org.springframework.web.bind.annotation.ResponseBody;
 7 import redis.clients.jedis.JedisCluster;
 8 
 9 @Controller
10 @RequestMapping("/redis")
11 public class RedisController {
12 
13     @Resource
14     private JedisCluster jedisCluster;
15     
16     @RequestMapping("/hello")
17     public @ResponseBody String sayHello(){
18         
19         for(int i = 0; i < 10; i++){
20             jedisCluster.set("name" + i, "hello" + i);
21         }
22         return "hello world!";
23     }
24 }

访问地址:http://localhost:8080/SpringRedisCluster/redis/hello.do ,进行测试。

9.源码下载

  点我下载

原文地址:https://www.cnblogs.com/xbq8080/p/6748641.html