您的位置:首页 > 数据库 > Redis

Spring 整合redis集群 实现 以及过程中需要注意的问题点

2017-03-24 20:23 901 查看

一,准备工作:

1.首先安装好redis集群,启动并配置集群。

2.SpringMVC环境,看项目或个人需要,可以使SpringMVC的web项目,也可以是只使用SpringBean管理器。

二,着手配置:

由于项目是由maven管理的所以需要的jar 包添加到maven 的pom文件即可

1.添加jar依赖,再maven pom.xml 文件中添加依赖如下:// 这里需要说明下,依赖的jar包 redis.client  和 spring-data-redis 的版本匹配问题 实验了好几个对应如下:

       redis.client  2.9.0 ---- spring-data-redis  1.7.1.RELEASE

       redis.client 2.9.0 -----spring-data-redis   1.7.2.RELEASE    这两个是可以使用的

       由于版本不匹配,遇到的错误如下:

         1. ClassNotFoundException  : redis/client/util/geoUtils    说这个类找不到。

         2. org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisTemplate' defined in class path resource [applicationContext.xml]

             说创建 redisTemplate bean 对象时失败了。

           <!-- jedis (一个redis client端的jar)-->

          <dependency>

            <groupId>redis.clients</groupId>

            <artifactId>jedis</artifactId>

            <version>2.9.0</version>

        </dependency>

         <!-- spring-data-redis 依赖-->

        <dependency>

            <groupId>org.springframework.data</groupId>

            <artifactId>spring-data-redis</artifactId>

            <version>1.7.1.RELEASE</version>

        </dependency>

2.配置redis 配置文件 我把它单独提取出来放在一个配置文件(spring-data-redis-cluster.xml)中,然后import 到 spring ApplicationContext.xml 文件中:

spring-data-redis-cluster.xml 配置如下:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"

    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"

    xmlns:task="http://www.springframework.org/schema/task" xmlns:mvc="http://www.springframework.org/schema/mvc"

    xmlns:cache="http://www.springframework.org/schema/cache"

    xsi:schemaLocation="

    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
    http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
    http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
     <!--  redis连接池  这里引用的是jedis 包中的功能  -->

    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">

        <property name="maxTotal" value="${redis.maxActive:1024}" />

        <property name="maxIdle" value="${redis.maxIdle:1024}" />

        <property name="maxWaitMillis" value="${redis.maxWait:10000}" />

        <property name="testOnBorrow" value="${redis.testOnBorrow:true}" />

        <property name="testOnReturn" value="${redis.testOnReturn:true}" />

    </bean>

    <!-- Redis集群配置     这里使用的是spring-data-redis  包中内容 -->

     <bean id="redisClusterConfig" class="org.springframework.data.redis.connection.RedisClusterConfiguration">

        <property name="maxRedirects" value="6"></property>

        <property name="clusterNodes">

            <set>

                <bean class="org.springframework.data.redis.connection.RedisNode">

                    <constructor-arg name="host" value="192.168.1.105"></constructor-arg>

                    <constructor-arg name="port" value="7111"></constructor-arg>

                </bean>

                <bean class="org.springframework.data.redis.connection.RedisNode">

                    <constructor-arg name="host" value="192.168.1.105"></constructor-arg>

                    <constructor-arg name="port" value="7112"></constructor-arg>

                </bean>

                <bean class="org.springframework.data.redis.connection.RedisNode">

                    <constructor-arg name="host" value="192.168.1.105"></constructor-arg>

                    <constructor-arg name="port" value="7116"></constructor-arg>

                </bean>

                <bean class="org.springframework.data.redis.connection.RedisNode">

                    <constructor-arg name="host" value="192.168.1.102"></constructor-arg>

                    <constructor-arg name="port" value="7113"></constructor-arg>

                </bean>

                 <bean class="org.springframework.data.redis.connection.RedisNode">

                    <constructor-arg name="host" value="192.168.1.102"></constructor-arg>

                    <constructor-arg name="port" value="7114"></constructor-arg>

                </bean>

                 <bean class="org.springframework.data.redis.connection.RedisNode">

                    <constructor-arg name="host" value="192.168.1.102"></constructor-arg>

                    <constructor-arg name="port" value="7115"></constructor-arg>

                </bean>

            </set>

        </property>

    </bean>

    <!-- Redis连接工厂     -->

    <bean id="redis4CacheConnectionFactory"

        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">

        <constructor-arg name="clusterConfig" ref="redisClusterConfig" />

        <property name="timeout" value="${redis.timeout:10000}" />

        <property name="poolConfig" ref="jedisPoolConfig" />

    </bean>

    <!-- 存储序列化 -->

    <bean name="stringRedisSerializer"

        class="org.springframework.data.redis.serializer.StringRedisSerializer" />

    <!-- 集群Resis使用模板 -->

    <bean id="clusterRedisTemplate" class="org.springframework.data.redis.core.RedisTemplate">

        <property name="connectionFactory" ref="redis4CacheConnectionFactory" />

        <property name="keySerializer" ref="stringRedisSerializer" />

        <property name="hashKeySerializer" ref="stringRedisSerializer" />

        <property name="valueSerializer" ref="stringRedisSerializer" />

        <property name="hashValueSerializer" ref="stringRedisSerializer" />

    </bean>

</beans>

3.再ApplicationContent.xml 配置文件中 导入以上配置:

<!-- 导入rediscluster配置文件 -->

    <import resource="classpath:spring-data-redis-cluster.xml" />

4.redisTemplate  的应用:

自定义一个redisClient类来管理操作 redis 的存取操作:我定义的是:RedisClusterClient.java 类,内容如下:

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

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.Service;

import org.springframework.util.StringUtils;

@Service

public class RedisClusterClient {

        // 由于在Spring ApplicationContext.xml 配置文件中导入了 redis的配置文件,也就间接的将 <bean id="clusterRedisTemplate"                                                                  class="org.springframework.data.redis.core.RedisTemplate">  这个Bean托管给了Spring bean容器来管理所以
只要我使用注解就可以把这个模板类对象引用过来。

       @Autowired

       private RedisTemplate<String,String> clusterRedisTemplate;

    

       //添加数据

        public void put(Object key, Object value) {

            if(null == value) {

                return;

            }

    

            if(value instanceof String) {

                if(StringUtils.isEmpty(value.toString())) {

                    return;

                }

            }

    

            // TODO Auto-generated method stub

            final String keyf = key + "";

            final Object valuef = value;

            final long liveTime = 86400;

    

            clusterRedisTemplate.execute(new RedisCallback<Long>() {

                public Long doInRedis(RedisConnection connection)

                        throws DataAccessException {

                    byte[] keyb = keyf.getBytes();

                    byte[] valueb = toByteArray(valuef);

                    connection.set(keyb, valueb);

                    if (liveTime > 0) {

                        connection.expire(keyb, liveTime);

                    }

                    return 1L;

                }

            });

        }

    

         // 获取数据

        public Object get(Object key) {

            final String keyf = (String) key;

            Object object;

            object = clusterRedisTemplate.execute(new RedisCallback<Object>() {

                public Object doInRedis(RedisConnection connection)

                        throws DataAccessException {

    

                    byte[] key = keyf.getBytes();

                    byte[] value = connection.get(key);

                    if (value == null) {

                        return null;

                    }

                    return toObject(value);

    

                }

            });

    

            return object;

        }

    

        /**

         * 描述 : <byte[]转Object>. <br>

         * <p>

         * <使用方法说明>

         * </p>

         *

         * @param bytes

         * @return

         */

        private Object toObject(byte[] bytes) {

            Object obj = null;

            try {

                ByteArrayInputStream bis = new ByteArrayInputStream(bytes);

                ObjectInputStream ois = new ObjectInputStream(bis);

                obj = ois.readObject();

                ois.close();

                bis.close();

            } catch (IOException ex) {

                ex.printStackTrace();

            } catch (ClassNotFoundException ex) {

                ex.printStackTrace();

            }

            return obj;

        }

    

        private byte[] toByteArray(Object obj) {

            byte[] bytes = null;

            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            try {

                ObjectOutputStream oos = new ObjectOutputStream(bos);

                oos.writeObject(obj);

                oos.flush();

                bytes = bos.toByteArray();

                oos.close();

                bos.close();

            } catch (IOException ex) {

                ex.printStackTrace();

            }

            return bytes;

        }

    

}

5.以上配置+实现。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐