`

spring集成redis,集成redis集群

 
阅读更多
1、通过spring-data-redis集成redis

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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.chen</groupId>
	<artifactId>test_redis02</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<build />
	<properties>
		<spring.version>3.1.2.RELEASE</spring.version>
	</properties>

	<dependencies>
		<dependency>
	<groupId>junit</groupId>
	<artifactId>junit</artifactId>
	<version>4.12</version>
</dependency>
		<!-- spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>


		<dependency>
	<groupId>redis.clients</groupId>
	<artifactId>jedis</artifactId>
	<version>2.8.1</version>
</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-redis</artifactId>
			<version>1.7.1.RELEASE</version>
		</dependency>
	 	<dependency>
 	<groupId>org.apache.commons</groupId>
	<artifactId>commons-pool2</artifactId>
	<version>2.4.2</version>
</dependency> 
	</dependencies>
</project>


spring application-reids.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"   
   	xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd  
    	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
    	">
    
    <!-- 加载配置文件 -->
    <context:property-placeholder location="classpath:redis.properties"/>
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
    	<property name="maxIdle" value="${redis.maxIdle}" />
    	<!-- <property name="maxActive" value="${redis.maxActive}" />
    	<property name="maxWait" value="${redis.maxWait}" />
    	<property name="testOnBorrow" value="${redis.testOnBorrow}" /> -->
    </bean>
    
    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"  
        p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}"  p:pool-config-ref="poolConfig"/> 
    
    <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">  
        <property name="connectionFactory"   ref="connectionFactory" />  
    </bean>       
    
</beans>




UserDaoImpl.java

package com.chen.dao;

import java.io.Serializable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import com.chen.pojo.User;
@Repository
public class UserDaoImpl implements UserDao {
	
	@Autowired
	private RedisTemplate<Serializable,Serializable> redisTemplate;

	public void saveUser(final User user) {
		redisTemplate.execute(new RedisCallback<Object>(){
			@Override
			public Object doInRedis(RedisConnection connection)
					throws DataAccessException {
				String str= "user.uid."+user.getId();
				byte[] key = redisTemplate.getStringSerializer().serialize(str);
				connection.set(key,redisTemplate.getStringSerializer().serialize(user.getName()));
				return null;
			}
		});
	}

	public User getUser(final long id) {
		return redisTemplate.execute(new RedisCallback<User>(){
			@Override
			public User doInRedis(RedisConnection connection) throws DataAccessException {
				byte[] key = redisTemplate.getStringSerializer().serialize("user.uid." + id);
				if(connection.exists(key)) {
					byte[] value = connection.get(key);
					String name = redisTemplate.getStringSerializer().deserialize(value);
					User user = new User();
					user.setName(name);
					user.setId(id);
					return user;
				}
				return null;
			}
		});
	}

}



详情见附件test_spring_data_redis02.rar源码

2、通过jedis集成redis

spring applicationContext.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"   
   	xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd  
    	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
    	">
    
    <!-- 加载配置文件 -->
    <context:property-placeholder location="classpath:redis.properties"/>
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
    	<property name="maxIdle" value="${redis.maxIdle}" />
    	<!-- <property name="maxActive" value="${redis.maxActive}" />
    	<property name="maxWait" value="${redis.maxWait}" />
    	<property name="testOnBorrow" value="${redis.testOnBorrow}" /> -->
    </bean>
    <bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool" scope="singleton">
    	<constructor-arg index="0" ref="jedisPoolConfig" />
    	<constructor-arg index="1">
    		<list>
    			<bean class="redis.clients.jedis.JedisShardInfo">
    				<constructor-arg name="host" value="${redis.host}" />
    				<constructor-arg name="port" value="${redis.port}" />
    				<!-- <constructor-arg name="timeout" value="${redis.timeout}" /> -->
    			</bean>
    		</list>
    	</constructor-arg>
    </bean>
      
    
</beans>




RedisDataSourceImpl.java
package com.chen.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
@Repository("redisDataSource")
public class RedisDataSourceImpl implements RedisDataSource {
	
	@Autowired
	private ShardedJedisPool shardedJedisPool;
	
	public ShardedJedis getRedisClient() {
		try{
			ShardedJedis shardJedis = shardedJedisPool.getResource();
			return shardJedis;
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}

	public void returnResource(ShardedJedis shardedJedis) {
		shardedJedisPool.returnResource(shardedJedis);
	}

	public void returnResource(ShardedJedis shardedJedis, boolean broken) {
		if(broken){
			shardedJedisPool.returnBrokenResource(shardedJedis);
		}else{
			shardedJedisPool.returnResource(shardedJedis);
		}
	}

}


RedisClientTemplate.java
package com.chen.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import redis.clients.jedis.ShardedJedis;

@Repository("redisClientTemplate")
public class RedisClientTemplate {
	@Autowired
	private RedisDataSource redisDataSource;
	
	public void disconnect(){
		ShardedJedis shardedJedis = redisDataSource.getRedisClient();
		shardedJedis.disconnect();
	}
	
	public String set(String key,String val){
		String result = null ;
		ShardedJedis jedis = redisDataSource.getRedisClient();
		if(jedis ==null)return null;
		boolean broken = false;
		try{
			result = jedis.set(key, val);
		}catch(Exception e){
			e.printStackTrace();
			broken = true ;
		}finally{
			redisDataSource.returnResource(jedis,broken);
		}
		return result;
	}
	
	public String get(String key){
		String result = null;
		ShardedJedis jedis = redisDataSource.getRedisClient();
		if(jedis==null)return result;
		boolean broken = false;
		try{
			result = jedis.get(key);
		}catch(Exception e){
			e.printStackTrace();
			broken= true;
		}finally{
			redisDataSource.returnResource(jedis,broken);
		}
		return result;
	}
}



DemoTest.java
package com.chen.demo;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.chen.redis.RedisClientTemplate;

public class DemoTest {
	private static ApplicationContext apx;
	static{
		apx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
	}
	
	@Test
	public void test1(){
		String key1 = "mykey1"; String val1 = "myvalue1";
		RedisClientTemplate template = (RedisClientTemplate) apx.getBean("redisClientTemplate");
		String result = template.set(key1, val1);
		System.out.println("result="+result);
	}
	
	@Test
	public void test2(){
		String key1 = "mykey1";
		RedisClientTemplate template = (RedisClientTemplate) apx.getBean("redisClientTemplate");
		String val1 = template.get(key1);
		System.out.println(val1);
	}
}



详情见test_spring_redis03.rar源码

3、通过jedis集成JedisCluster

spring applicationContext.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"   
   	xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd  
    	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
    	">
    
    <!-- 加载配置文件 -->
    <context:property-placeholder location="classpath:redis.properties"/>
    <bean name="genericObjectPoolConfig" class="org.apache.commons.pool2.impl.GenericObjectPoolConfig">
    	<property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
    	<property name="maxTotal" value="${redis.maxTotal}" />
    	<property name="minIdle" value="${redis.minIdle}" />
    	<property name="maxIdle" value="${redis.maxIdle}" />
    </bean>
    
    <bean id="jedisCluster" class="com.chen.redis.JedisClusterFactory">
    	<property name="addressConfig">
    		<value>classpath:connect-redis.properties</value>
    	</property>
    	<property name="addressKeyPrefix" value="address"></property>
    	<property name="timeout" value="${redis.timeout}" />
    	<property name="maxRedirections" value="${redis.maxRedirections}" />
    	<property name="genericObjectPoolConfig" ref="genericObjectPoolConfig"></property>
    </bean>
    
</beans>



集群服务器配置文件
connect-redis.properties
address1=192.168.199.130:7001
address2=192.168.199.130:7002
address3=192.168.199.130:7003
address4=192.168.199.130:7004
address5=192.168.199.130:7005
address6=192.168.199.130:7006




JedisClusterFactory.java
package com.chen.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;

public class JedisClusterFactory implements FactoryBean<JedisCluster>, InitializingBean {

	private Resource addressConfig;
	private String addressKeyPrefix ;

	private JedisCluster jedisCluster;
	private Integer timeout;
	private Integer maxRedirections;
	private GenericObjectPoolConfig genericObjectPoolConfig;
	
	private Pattern p = Pattern.compile("^.+[:]\\d{1,5}\\s*$");

	@Override
	public JedisCluster getObject() throws Exception {
		return jedisCluster;
	}

	@Override
	public Class<? extends JedisCluster> getObjectType() {
		return (this.jedisCluster != null ? this.jedisCluster.getClass() : JedisCluster.class);
	}

	@Override
	public boolean isSingleton() {
		return true;
	}



	private Set<HostAndPort> parseHostAndPort() throws Exception {
		try {
			Properties prop = new Properties();
			prop.load(this.addressConfig.getInputStream());

			Set<HostAndPort> haps = new HashSet<HostAndPort>();
			for (Object key : prop.keySet()) {

				if (!((String) key).startsWith(addressKeyPrefix)) {
					continue;
				}

				String val = (String) prop.get(key);

				boolean isIpPort = p.matcher(val).matches();

				if (!isIpPort) {
					throw new IllegalArgumentException("ip 或 port 不合法");
				}
				String[] ipAndPort = val.split(":");

				HostAndPort hap = new HostAndPort(ipAndPort[0], Integer.parseInt(ipAndPort[1]));
				haps.add(hap);
			}

			return haps;
		} catch (IllegalArgumentException ex) {
			throw ex;
		} catch (Exception ex) {
			throw new Exception("解析 jedis 配置文件失败", ex);
		}
	}
	
	@Override
	public void afterPropertiesSet() throws Exception {
		Set<HostAndPort> haps = this.parseHostAndPort();
		
		jedisCluster = new JedisCluster(haps, timeout, maxRedirections,genericObjectPoolConfig);
		
	}
	public void setAddressConfig(Resource addressConfig) {
		this.addressConfig = addressConfig;
	}

	public void setTimeout(int timeout) {
		this.timeout = timeout;
	}

	public void setMaxRedirections(int maxRedirections) {
		this.maxRedirections = maxRedirections;
	}

	public void setAddressKeyPrefix(String addressKeyPrefix) {
		this.addressKeyPrefix = addressKeyPrefix;
	}

	public void setGenericObjectPoolConfig(GenericObjectPoolConfig genericObjectPoolConfig) {
		this.genericObjectPoolConfig = genericObjectPoolConfig;
	}

}



DemoTest.java
package com.chen.demo;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import redis.clients.jedis.JedisCluster;

public class DemoTest {
	private static ApplicationContext apx;
	static{
		apx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
	}
	
	
	@Test
	public void test1(){
		JedisCluster jedisCluster = (JedisCluster) apx.getBean("jedisCluster");
		String key1="myname1";
		String key2="myname2";
		String key3="myname3";
		System.out.println(jedisCluster.get(key1));
		System.out.println(jedisCluster.get(key2));
		System.out.println(jedisCluster.get(key3));
		
	}
	
	@Test
	public void test2(){
		JedisCluster jedisCluster = (JedisCluster) apx.getBean("jedisCluster");
		String key1="mystring1"; String val1 = "myval1";
		String key2="mystring2"; String val2 = "myval2";
		String key3="mystring3"; String val3 = "myval3";
		System.out.println(jedisCluster.set(key1,val1));
		System.out.println(jedisCluster.set(key2,val2));
		System.out.println(jedisCluster.set(key3,val3));
		System.out.println("----------------------");
		System.out.println(jedisCluster.get(key1));
		System.out.println(jedisCluster.get(key2));
		System.out.println(jedisCluster.get(key3));
	}
}



详情见源码:test_spring_cluster_redis04.rar
分享到:
评论

相关推荐

    Spring集成redis集群

    **Spring集成Redis集群详解** 在现代的Web应用程序开发中,数据缓存扮演着至关重要的角色,而Redis作为一款高性能的键值数据存储系统,被广泛应用于缓存、消息队列等多个场景。当业务规模扩大,单机Redis可能无法...

    spring集成redis单节点、集群、哨兵配置

    接下来是**Redis集群配置**。在集群模式下,Redis数据分散在多个节点上,每个节点只负责一部分数据,提高扩展性和可用性。Spring Data Redis提供了ClusterConnectionFactory来处理集群连接。配置需要指定所有节点的...

    spring集成redis集群需要的jar.zip

    Spring + redis集群的集成 spring-data-redis-1.8.1.RELEASE.jar jedis-2.9.0.jar spring-data-commons-1.8.1.RELEASE.jar commons-pool2-2.4.2.jar

    springcloud部署redis集群

    在SpringCloud框架中,部署Redis集群是实现高可用、数据持久化和分布式缓存的关键步骤。Redis是一款高性能的键值数据库,广泛应用于缓存、消息队列等多种场景。SpringCloud通过集成Spring Data Redis模块,使得在...

    spring + redis集群

    本文将深入探讨如何使用Spring Data Redis构建一个Redis集群,以及如何通过Spring框架来操作Redis集群,存储对象集合,并提供一个基于Maven的可运行项目示例。 首先,Spring Data Redis是Spring框架的一个模块,它...

    springboot整合redis集群零配置

    在Spring Boot 2.1及以上版本中,我们可以利用`spring.redis.cluster.nodes`属性来实现零配置连接到Redis集群,只需将所有集群节点的IP和端口以逗号分隔的形式列出即可,如: ```properties spring.redis.cluster....

    SpringBoot集成Redis集群

    SpringBoot集成Redis集群 在本文档中,我们将指导您如何在SpringBoot 2.X中集成Redis集群。下面是相关的知识点: 集成Redis集群的必要性 在实际应用中,使用Redis集群可以提高系统的可扩展性和可靠性。Redis集群...

    Spring集成Redis集群的配置文件

    Spring集成Redis集群的配置文件

    springboot集成redis集群,redis安装包配置

    在本文中,我们将深入探讨如何在SpringBoot应用中集成Redis集群以及如何配置Redis服务器。首先,Redis是一个开源的、基于键值对的数据存储系统,常用于数据库、缓存和消息中间件。它以其高性能和易用性而备受青睐。...

    SpringMVC整合Redis集群

    项目由maven构建,使用springMVC整合了Redis的集群,发布到tomcat中,访问http://localhost:8080/SpringRedisCluster/redis/hello.do测试即可,前提是配好了redis的集群。

    redis-cluster和spring集成,基于cache注解

    综上所述,"redis-cluster和spring集成,基于cache注解" 的项目是一个使用 Spring Cache 集成 Redis 集群的实例,旨在通过注解的方式简化缓存管理,提高应用性能。开发者可以通过导入提供的项目,快速了解和实践这一...

    spring整合redis(spring模板+连接池+哨兵+json序列化+集群).rar

    最后,当涉及到Redis集群时,多个Redis实例协同工作以提供更大的存储空间和更高的可用性。Spring Data Redis同样支持集群模式,你需要配置集群节点的地址列表,Spring会自动处理槽的分布和操作的路由。 在`redis....

    spring4.3jar包和spring4.3匹配的redis jar包

    最近项目需要用到redis,在原有项目配置redis配好了但是一直报错,百度了下都是说spring的jar包和redis的包不匹配,最后把spring的版本换了,这是spring4.3jar包和匹配的redis jar包。

    RedisCluster集群(Spring访问Redis)

    **RedisCluster集群与Spring访问Redis详解** Redis是一个高性能的键值数据库,广泛应用于缓存、消息中间件等场景。在大型分布式系统中,为了提供高可用性和数据冗余,我们通常会采用Redis Cluster来构建集群。本文...

    Spring+redis整合demo2

    这个模块提供了对Redis操作的抽象,使得开发者可以方便地在Spring应用中集成Redis,利用其高速缓存和持久化能力。 **1. 添加依赖** 要整合Spring与Redis,首先要在项目中添加Spring Data Redis和Jedis(或Lettuce)...

    redis集群连接及工具类DEMO

    【Redis集群连接及工具类DEMO】是一个Spring...通过学习和分析这个DEMO,开发者可以掌握Spring与Redis集群的集成方法,了解如何编写和使用工具类以简化开发流程,同时加深对Redis数据结构和命令的理解,提高开发效率。

    springboot整合redis集群(三种方式)源码

    springboot整合redis集群(三种方式)源码

Global site tag (gtag.js) - Google Analytics