1.pom.xml

 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.xbq.redis</groupId>
<artifactId>SpringRedisCluster</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SpringRedisCluster Maven Webapp</name>
<url>http://maven.apache.org</url> <properties>
<org.springframework.version>4.2.2.RELEASE</org.springframework.version>
</properties> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency> <dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!-- 日志处理 -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<!-- redis依赖 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.3</version>
</dependency>
<!-- spring依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- jacksoon依赖 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.8.7</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.1</version>
<classifier>jdk15</classifier>
</dependency>
</dependencies> <build>
<finalName>SpringRedisCluster</finalName>
</build>
</project>

2.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"
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>SpringRedisCluster</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list> <!--配置字符过滤器-->
<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>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param> <!-- 添加对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>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>

3.spring配置,applicationContext.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:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
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"
default-lazy-init="true"> <description>Spring公共配置</description> <!-- 使用annotation 自动注册bean,并检查@Required,@Autowired的属性已被注入 -->
<context:component-scan base-package="com.xbq"/>
<context:annotation-config />
<!-- redis配置 -->
<import resource="classpath:redis.xml"/>
</beans>

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

 <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.2.xsd"> <!-- 解决springMVC响应数据乱码 text/plain就是响应的时候原样返回数据 -->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven> <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
<context:component-scan base-package="com.*.controller" /> <!-- 视图解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp"></property>
</bean> <!-- 控制器异常处理 -->
<bean id="exceptionResolver"
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.lang.Exception">
error
</prop>
</props>
</property>
</bean>
</beans>

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

 package com.xbq.redis;

 import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Pattern; import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource; import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster; /**
* Jedis集群工厂
* @author xbq
* @Date 2017-05-14
*/
public class JedisClusterFactory implements InitializingBean,FactoryBean<JedisCluster>{ private Resource addressConfig; // 下面变量 对应spring redis配置文件中的 property的name
private JedisCluster jedisCluster;
private String addressKeyPrefix;
private Integer timeout;
private Integer maxRedirections;
private GenericObjectPoolConfig genericObjectPoolConfig; // 正则表达式 匹配 ip和port
private Pattern p = Pattern.compile("^.+[:]\\d{1,5}\\s*$"); /**
* 实现 InitializingBean 的接口,初始化的 得到 jedisCluster
*/
public void afterPropertiesSet() throws Exception {
Set<HostAndPort> jedisClusterNode= this.parseHostAndPort();
jedisCluster = new JedisCluster(jedisClusterNode, timeout, maxRedirections, genericObjectPoolConfig);
} /**
* 实现 FactoryBean 的接口
* 获取 jedisCluster对象
*/
public JedisCluster getObject() throws Exception {
return jedisCluster;
} /**
* 实现 FactoryBean 的接口
* 获取 jedisCluster的类型
*/
public Class<? extends JedisCluster> getObjectType() {
return (jedisCluster != null ? this.jedisCluster.getClass() : JedisCluster.class);
} /**
* 实现 FactoryBean 的接口
*/
public boolean isSingleton() {
return true;
} /**
* 解析Jedis配置文件,看是否满足 IP和端口
* @return
*/
private Set<HostAndPort> parseHostAndPort() throws Exception{
Set<HostAndPort> hostAndPorts = new HashSet<HostAndPort>();
try {
Properties properties = new Properties();
properties.load(this.addressConfig.getInputStream()); for(Object key : properties.keySet()){
// 如果key不是以 addressKeyPrefix的值 开头,则continue
if(!((String)key).startsWith(addressKeyPrefix)){
continue;
}
// 根据 key从properties中取出值
String valus = (String) properties.get(key);
// 判断取出的value是否是ip和port
boolean isIPProt = p.matcher(valus).matches();
if(!isIPProt){
throw new IllegalArgumentException("ip和port不合法!");
}
String[] ipAndPort = valus.split(":");
HostAndPort hostAndPort = new HostAndPort(ipAndPort[0], Integer.parseInt(ipAndPort[1]));
hostAndPorts.add(hostAndPort);
}
} catch (Exception e) {
throw new Exception("解析 jedis 配置文件失败!");
}
return hostAndPorts;
} // set方法
public void setJedisCluster(JedisCluster jedisCluster) {
this.jedisCluster = jedisCluster;
}
public void setAddressKeyPrefix(String addressKeyPrefix) {
this.addressKeyPrefix = addressKeyPrefix;
}
public void setTimeout(Integer timeout) {
this.timeout = timeout;
}
public void setMaxRedirections(Integer maxRedirections) {
this.maxRedirections = maxRedirections;
}
public void setGenericObjectPoolConfig(GenericObjectPoolConfig genericObjectPoolConfig) {
this.genericObjectPoolConfig = genericObjectPoolConfig;
}
public void setAddressConfig(Resource addressConfig) {
this.addressConfig = addressConfig;
}
}

8.控制层,RedisController.java

 package com.xbq.controller;

 import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.JedisCluster; @Controller
@RequestMapping("/redis")
public class RedisController { @Resource
private JedisCluster jedisCluster; @RequestMapping("/hello")
public @ResponseBody String sayHello(){ for(int i = 0; i < 10; i++){
jedisCluster.set("name" + i, "hello" + i);
}
return "hello world!";
}
}

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

9.源码下载

  点我下载

Redis(七)-- SpringMVC整合Redis集群的更多相关文章

  1. Redis(七):Jedis简介和集群

    Jedis简介 1.Jedis 是Redis 客户端工具jar2.使用非集群版示例代码 Jedis jedis = new Jedis("192.168.139.132", 637 ...

  2. Redis之高可用、集群、云平台搭建

    原文:Redis之高可用.集群.云平台搭建 文章大纲 一.基础知识学习二.Redis常见的几种架构及优缺点总结三.Redis之Redis Sentinel(哨兵)实战四.Redis之Redis Clu ...

  3. Redis学习笔记八:集群模式

    作者:Grey 原文地址:Redis学习笔记八:集群模式 前面提到的Redis学习笔记七:主从复制和哨兵只能解决Redis的单点压力大和单点故障问题,接下来要讲的Redis Cluster模式,主要是 ...

  4. springmvc整合redis架构搭建实例

    新换环境,又有新东西可以学习了,哈皮! 抽空学习之余看了一下redis,个人对Springmvc的爱是忠贞不渝,所以整理了一下Springmvc整合redis的环境搭建.分享学习. 第一步: 创建ma ...

  5. 关于redis主从|哨兵|集群模式

    关于redis主从.哨兵.集群的介绍网上很多,这里就不赘述了. 一.主从 通过持久化功能,Redis保证了即使在服务器重启的情况下也不会损失(或少量损失)数据,因为持久化会把内存中数据保存到硬盘上,重 ...

  6. 深入学习Redis(5):集群

    前言 在前面的文章中,已经介绍了Redis的几种高可用技术:持久化.主从复制和哨兵,但这些方案仍有不足,其中最主要的问题是存储能力受单机限制,以及无法实现写操作的负载均衡. Redis集群解决了上述问 ...

  7. Redis 实战篇之搭建集群

    Redis 集群简介# Redis Cluster 即 Redis 集群,是 Redis 官方在 3.0 版本推出的一套分布式存储方案.完全去中心化,由多个节点组成,所有节点彼此互联.Redis 客户 ...

  8. Redis.之.环境搭建(集群)

    Redis.之.环境搭建(集群) 现有环境: /u01/app/ |- redis # 单机版 |- redis-3.2.12    # redis源件 所需软件:redis-3.0.0.gem -- ...

  9. redis主从架构,分片集群详解

    写在前面:这篇笔记有点长,如果你认真看完,收获会不少,如果你只是忘记了相关命令,请翻到末尾. redis的简单介绍: 一个提供多种数据类类型储存,整个系统都在内存中运行的, 定期通过异步的方式把数据刷 ...

  10. Spring Boot+redis存储session,满足集群部署、分布式系统的session共享

    本文讲述spring-boot工程中使用spring-session机制进行安全认证,并且通过redis存储session,满足集群部署.分布式系统的session共享. 原文链接:https://w ...

随机推荐

  1. RTX——第7章 任务管理

    以下内容转载自安富莱电子: http://forum.armfly.com/forum.php 单任务系统学习多任务系统之前,我们先来回顾下单任务系统的编程框架,即裸机时的编程框架. 裸机编程主要是采 ...

  2. string.h中的库函数

    虽然面试的时候,都会叫你不使用c库函数,自己完成某某函数的编写,但是库函数毕竟更让人信赖,我们没有任何理由怀疑库函数而使用自己的版本.不过当做练习,自己还是可以实现一下的.这里记录一下5th c pr ...

  3. pyqt重写键盘事件+获取信号发送对象

    # _*_ coding:utf-8 _*_ import sys from PyQt4 import QtGui,QtCore class Example(QtGui.QMainWindow): d ...

  4. ubuntu下man帮助文档不全怎么办?如何解决?

    真心后悔用ubuntu学习linux 发现很多东西不全,kate没有,vi版本低,帮助文档不全一系列的问题.ubuntu下man帮助文档不全怎么办?如何解决?不用担心,下边小编就为大家带来最详细的解决 ...

  5. Jackson2.1.4 序列化对象时,过滤null的属性 empty的属性 default的属性

    在进行序列化如何过滤为null的属性,empty的属性,或者default的属性. 一.全局注册 objectMapper.setSerializationInclusion(Include.ALWA ...

  6. [Linux小技巧] 一行命令让CPU占用率达到100%

    for i in `seq 1 $(cat /proc/cpuinfo |grep "physical id" |wc -l)`; do dd if=/dev/zero of=/d ...

  7. javascript-限制文本框只输入数字

    使用onInput()事件 oninput 是 HTML5 的标准事件,对于检测 textarea, input:text, input:password 和 input:search 这几个元素通过 ...

  8. golang 数组以及slice切片

    老虞学GoLang笔记-数组和切片   数组 Arrays 数组是内置(build-in)类型,是一组同类型数据的集合,它是值类型,通过从0开始的下标索引访问元素值.在初始化后长度是固定的,无法修改其 ...

  9. css样式DEMO

    <!-- 导入框 --> <div id="importWin" class="easyui-window" title="服务封装 ...

  10. numpy得到数组的index

    itemindex = numpy.where(array==item)