Redis(七)-- SpringMVC整合Redis集群
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集群的更多相关文章
- Redis(七):Jedis简介和集群
Jedis简介 1.Jedis 是Redis 客户端工具jar2.使用非集群版示例代码 Jedis jedis = new Jedis("192.168.139.132", 637 ...
- Redis之高可用、集群、云平台搭建
原文:Redis之高可用.集群.云平台搭建 文章大纲 一.基础知识学习二.Redis常见的几种架构及优缺点总结三.Redis之Redis Sentinel(哨兵)实战四.Redis之Redis Clu ...
- Redis学习笔记八:集群模式
作者:Grey 原文地址:Redis学习笔记八:集群模式 前面提到的Redis学习笔记七:主从复制和哨兵只能解决Redis的单点压力大和单点故障问题,接下来要讲的Redis Cluster模式,主要是 ...
- springmvc整合redis架构搭建实例
新换环境,又有新东西可以学习了,哈皮! 抽空学习之余看了一下redis,个人对Springmvc的爱是忠贞不渝,所以整理了一下Springmvc整合redis的环境搭建.分享学习. 第一步: 创建ma ...
- 关于redis主从|哨兵|集群模式
关于redis主从.哨兵.集群的介绍网上很多,这里就不赘述了. 一.主从 通过持久化功能,Redis保证了即使在服务器重启的情况下也不会损失(或少量损失)数据,因为持久化会把内存中数据保存到硬盘上,重 ...
- 深入学习Redis(5):集群
前言 在前面的文章中,已经介绍了Redis的几种高可用技术:持久化.主从复制和哨兵,但这些方案仍有不足,其中最主要的问题是存储能力受单机限制,以及无法实现写操作的负载均衡. Redis集群解决了上述问 ...
- Redis 实战篇之搭建集群
Redis 集群简介# Redis Cluster 即 Redis 集群,是 Redis 官方在 3.0 版本推出的一套分布式存储方案.完全去中心化,由多个节点组成,所有节点彼此互联.Redis 客户 ...
- Redis.之.环境搭建(集群)
Redis.之.环境搭建(集群) 现有环境: /u01/app/ |- redis # 单机版 |- redis-3.2.12 # redis源件 所需软件:redis-3.0.0.gem -- ...
- redis主从架构,分片集群详解
写在前面:这篇笔记有点长,如果你认真看完,收获会不少,如果你只是忘记了相关命令,请翻到末尾. redis的简单介绍: 一个提供多种数据类类型储存,整个系统都在内存中运行的, 定期通过异步的方式把数据刷 ...
- Spring Boot+redis存储session,满足集群部署、分布式系统的session共享
本文讲述spring-boot工程中使用spring-session机制进行安全认证,并且通过redis存储session,满足集群部署.分布式系统的session共享. 原文链接:https://w ...
随机推荐
- fread和fwrite函数功能
fread和fwrite函数功能 用来读写一个数据块. 一般调用形式 fread(buffer,size,count,fp); fwrite(buffer,size,count,fp); ...
- JavaScript 使用 php 的变量
php 里面有一个变量,我想让 js 调用他, 有如下流程: <?php for ($i = 0; $i < 8; $i++) { echo "<tr>"; ...
- Oracle数据误删除的恢复操作
flashbackup 闪回操作: 1. 打开表的闪回功能: alter table dw_stg.fm_user_play_d enable row movement; 2. 查询要闪回的表的记录信 ...
- mac上php+nginx配置
brew的安装: ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)”php安装和配置bre ...
- 缓存之 ACache
1.android缓存的介绍 Android开发本质上就是手机和互联网中的webserver之间进行通信,就必定须要从服务端获取数据.而重复通过网络获取数据是比較耗时的.特别是訪问比較多的时候.会极大 ...
- synchronize模块
synchronize模块 使用rsync同步文件,其参数如下: archive: 归档,相当于同时开启recursive(递归).links.perms.times.owner.group.-D选项 ...
- Web API(一);Restful架构
一.什么是RESTful REST全称是Representational State Transfer,中文意思是表述(编者注:通常译为表征)性状态转移.REST指的是一组架构约束条件和原则.如果一个 ...
- Game publishing request was abnormally terminated (ID 27492).
本地可以正常发布:远程发布报错.怀疑跟直接删除数据库记录有关,wp_myarcadegames/wp_posts Game publishing request was abnormally term ...
- e557. 在Applet中显示图片
See also e551 精简的Applet. Image image; public void init() { // Load image image = getImage(getDocumen ...
- 关于多层for循环迭代的效率优化问题
关于多层for循环迭代的效率优化问题 今天笔试的时候遇到这么一道题目 说有上面这么循环嵌套 .问怎么优化 并说明原因. for(int i = 0 ; i < 1000 ;i++){ ...