【冠亚体育手机网站】Redis集群与SSM整合使用方法,mybatis二级缓存

SSM+redis整合

首先是创建redis-cluster文件夹:

ssm框架之前已经搭建过了,这里不再做代码复制工作。

冠亚体育手机网站 1

这里主要是利用redis去做mybatis的二级缓存,mybaits映射文件中所有的select都会刷新已有缓存,如果不存在就会新建缓存,所有的insert,update操作都会更新缓存。

因为redis最少需要6个节点(三主三从),为了更好的理解,我这里创建了两台虚拟机(192.168.0.109
192.168.0.110),分别在两台虚拟机的/opt/redis-4.0.1/redis-cluster下创建三个节点文件夹

redis的好处也显而易见,可以使系统的数据访问性能更高。本节只是展示了整合方法和效果,后面会补齐redis集群、负载均衡和session共享的文章。

192.168.0.109:

下面就开始整合工作:

冠亚体育手机网站 2

冠亚体育手机网站 3

192.168.0.110:

后台首先启动redis-server(后台启动与远程连接linux服务的方法都需要改redis.conf文件),启动命令“./src/redis-server
./redis.conf”

冠亚体育手机网站 4

我这里是windows系统下开发的,推荐一个可视化工具“Redis Desktop
manager”,需要远程连接linux下的redis,需要linux下开启端口对外开放(具体方法是修改/etc/sysconfig/iptables文件,增加对外端口开发命令)。

以上6个节点全部创建完成,分别再在这六个文件夹下创建redis.conf配置文件,其中配置如图:

以上操作都完成后,即可远程连接成功了,如图:

port 7000
bind 192.168.0.109
daemonize yes
pidfile /var/run/redis_7000.pid
cluster-enabled yes
cluster-config-file nodes_7000.conf
cluster-node-timeout 10000
appendonly yes

冠亚体育手机网站 5

其中需要将port pidfile
cluster-config-file修改成节点端口号一致,bind改成本机ip,以便远程访问,全部修改完后,即可启动redis服务:

冠亚体育手机网站 6

启动命令:

现在还没有缓存记录,下面进入代码阶段,首先在pom.xml中增加需要的redis
jar包

192.168.0.109下的命令:“for((i=0;i<=2;i++)); do
/opt/redis-4.0.1/src/redis-server
/opt/redis-4.0.1/redis-cluster/700$i/redis.conf; done”

<dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-redis</artifactId>
      <version>1.6.2.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-ehcache</artifactId>
      <version>1.0.0</version>
    </dependency>
     <!-- 添加druid连接池包 -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.0.24</version>
    </dependency>

192.168.0.110下的命令:“for((i=3;i<=5;i++)); do
/opt/redis-4.0.1/src/redis-server
/opt/redis-4.0.1/redis-cluster/700$i/redis.conf; done”

pom.xml写好后,还需要新增两个配置文件:redis.properties

冠亚体育手机网站 7

redis.host=192.168.0.109
redis.port=6379
redis.pass=123456
redis.maxIdle=200
redis.maxActive=1024
redis.maxWait=10000
redis.testOnBorrow=true

可以看到后台模式启动成功的日志打印,两天机器都需要依次启动所有节点。节点启动完成后,即可创建集群服务:

其中字段也都很好理解,再加入配置文件:spring-redis.xml

在其中一台虚拟机上执行如下命令“/opt/redis-4.0.1/src/redis-trib.rb create
–replicas 1 192.168.0.109:7000 192.168.0.109:7001 192.168.0.109:7002
192.168.0.110:7003 192.168.0.110:7004 192.168.0.110:7005”

<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:mvc="http://www.springframework.org/schema/mvc"
 xmlns:util="http://www.springframework.org/schema/util"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:task="http://www.springframework.org/schema/task" 
 xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
   http://www.springframework.org/schema/util
   http://www.springframework.org/schema/util/spring-util-4.3.xsd
   http://www.springframework.org/schema/mvc
   http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-4.3.xsd">
  <!-- 连接池基本参数配置,类似数据库连接池 -->
   <context:property-placeholder location="classpath*:redis.properties" />
  <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
    <property name="maxTotal" value="${redis.maxActive}"/>
    <property name="maxIdle" value="${redis.maxIdle}" />
    <property name="testOnBorrow" value="${redis.testOnBorrow}"/>
  </bean>
  <!-- 连接池配置,类似数据库连接池 -->
  <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" >
    <property name="hostName" value="${redis.host}"></property>
    <property name="port" value="${redis.port}"></property>
    <property name="password" value="${redis.pass}"></property>
    <property name="poolConfig" ref="poolConfig"></property> 
  </bean>
  <!-- 调用连接池工厂配置 -->
  <!-- <bean id="redisTemplate" class=" org.springframework.data.redis.core.RedisTemplate">
    <property name="jedisConnectionFactory" ref="jedisConnectionFactory"></property>
    如果不配置Serializer,那么存储的时候智能使用String,如果用User类型存储,那么会提示错误User can't cast to String!!! 
     <property name="keySerializer"> 
      <bean 
      class="org.springframework.data.redis.serializer.StringRedisSerializer" /> 
    </property> 
    <property name="valueSerializer"> 
      <bean 
        class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" /> 
    </property> 
  </bean> -->
  <bean id="redisCacheTransfer" class="com.cjl.util.RedisCacheTransfer">
    <property name="jedisConnectionFactory" ref="jedisConnectionFactory" />
  </bean>
</beans>

冠亚体育手机网站 8

配置文件写好后,就开始java代码的编写:

 千万记住只需要在一台上执行即可,如果卡在join处不能往下执行,一般情况是出在防火墙端口被禁导致,有两种方式可以解决:

JedisClusterFactory.java

1、不但需要开启7000对外端口,还需要开启17000(因为redis总线端口需要加1000)。

package com.cjl.util;
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*$");
  public JedisCluster getObject() throws Exception {
    return jedisCluster;
  }
  public Class<? extends JedisCluster> getObjectType() {
    return (this.jedisCluster != null ? this.jedisCluster.getClass() : JedisCluster.class);
  }
  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);
    }
  }
  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;
  }
}

2、直接关闭所有防火墙(因我这里是自己的环境,所以直接关闭了防火墙服务)。

RedisCache.java

出现上图运行日志,基本就成功搭建好了集群服务,可以清晰的看到各个节点的主从关系,环境搭建好后,这里我们就和我上篇写到的SSM架构进行联合使用。

package com.cjl.util;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.jedis.JedisConnection;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import redis.clients.jedis.exceptions.JedisConnectionException;
public class RedisCache implements Cache {
  private static final Logger logger = LoggerFactory.getLogger(RedisCache.class);
  private static JedisConnectionFactory jedisConnectionFactory;
  private final String id;
  private final ReadWriteLock rwl = new ReentrantReadWriteLock();
  public RedisCache(final String id) {
    if (id == null) {
      throw new IllegalArgumentException("Cache instances require an ID");
    }
    logger.debug("MybatisRedisCache:id=" + id);
    this.id = id;
  }
  /**
   * 清空所有缓存
   */
  public void clear() {
    rwl.readLock().lock();
    JedisConnection connection = null;
    try {
      connection = jedisConnectionFactory.getConnection();
      connection.flushDb();
      connection.flushAll();
    } catch (JedisConnectionException e) {
      e.printStackTrace();
    } finally {
      if (connection != null) {
        connection.close();
      }
      rwl.readLock().unlock();
    }
  }
  public String getId() {
    return this.id;
  }
  /**
   * 获取缓存总数量
   */
  public int getSize() {
    int result = 0;
    JedisConnection connection = null;
    try {
      connection = jedisConnectionFactory.getConnection();
      result = Integer.valueOf(connection.dbSize().toString());
      logger.info("添加mybaits二级缓存数量:" + result);
    } catch (JedisConnectionException e) {
      e.printStackTrace();
    } finally {
      if (connection != null) {
        connection.close();
      }
    }
    return result;
  }
  public void putObject(Object key, Object value) {
    rwl.writeLock().lock();
    JedisConnection connection = null;
    try {
      connection = jedisConnectionFactory.getConnection();
      RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
      connection.set(SerializeUtil.serialize(key), SerializeUtil.serialize(value));
      logger.info("添加mybaits二级缓存key=" + key + ",value=" + value);
    } catch (JedisConnectionException e) {
      e.printStackTrace();
    } finally {
      if (connection != null) {
        connection.close();
      }
      rwl.writeLock().unlock();
    }
  }
  public Object getObject(Object key) {
    // 先从缓存中去取数据,先加上读锁
    rwl.readLock().lock();
    Object result = null;
    JedisConnection connection = null;
    try {
      connection = jedisConnectionFactory.getConnection();
      RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
      result = serializer.deserialize(connection.get(serializer.serialize(key)));
      logger.info("命中mybaits二级缓存,value=" + result);
    } catch (JedisConnectionException e) {
      e.printStackTrace();
    } finally {
      if (connection != null) {
        connection.close();
      }
      rwl.readLock().unlock();
    }
    return result;
  }
  public Object removeObject(Object key) {
    rwl.writeLock().lock();
    JedisConnection connection = null;
    Object result = null;
    try {
      connection = jedisConnectionFactory.getConnection();
      RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
      result = connection.expire(serializer.serialize(key), 0);
    } catch (JedisConnectionException e) {
      e.printStackTrace();
    } finally {
      if (connection != null) {
        connection.close();
      }
      rwl.writeLock().unlock();
    }
    return result;
  }
  public static void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
    RedisCache.jedisConnectionFactory = jedisConnectionFactory;
  }
  public ReadWriteLock getReadWriteLock() {
    // TODO Auto-generated method stub
    return rwl;
  }
}

上次整合的mybaits二级缓存是个单机版本,由于这种方式不支持集群,所以这里从新使用jedis-cluster进行另外一种redis集群与java整合使用的方式。

RedisCacheTransfer.java

首先在redis.properties文件中新增集群机器的配置,将6个节点依次加入配置:

package com.cjl.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
/**
 * 静态注入中间类
 */
public class RedisCacheTransfer {
   @Autowired
    public void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
      RedisCache.setJedisConnectionFactory(jedisConnectionFactory);
    }
}
#cluster 
cluster1.host.port=192.168.0.109:7000
cluster2.host.port=192.168.0.109:7001
cluster3.host.port=192.168.0.109:7002
cluster4.host.port=192.168.0.110:7003
cluster5.host.port=192.168.0.110:7004
cluster6.host.port=192.168.0.110:7005

SerializeUtil.java

redis配置文件中也与之前改动比较多,我直接列出来,可以直接拷去用了。

package com.cjl.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
 * 
 * @author cjl
 *
 */
public class SerializeUtil {
  /**
   * 序列化
   */
  public static byte[] serialize(Object object) {
    ObjectOutputStream oos = null;
    ByteArrayOutputStream baos = null;
    try {
      // 序列化
      baos = new ByteArrayOutputStream();
      oos = new ObjectOutputStream(baos);
      oos.writeObject(object);
      byte[] bytes = baos.toByteArray();
      return bytes;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
  /**
   *反序列化
   */
  public static Object unserialize(byte[] bytes) {
    if (bytes !=null) {
      ByteArrayInputStream bais = null;
      try {
        // 反序列化
        bais = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = new ObjectInputStream(bais);
        return ois.readObject();
      } catch (Exception e) {
      }
    } 
    return null;
  }
}

spring-redis.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:mvc="http://www.springframework.org/schema/mvc"
 xmlns:util="http://www.springframework.org/schema/util"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:task="http://www.springframework.org/schema/task" 
 xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
   http://www.springframework.org/schema/util
   http://www.springframework.org/schema/util/spring-util-4.3.xsd
   http://www.springframework.org/schema/mvc
   http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-4.3.xsd">
  <!-- 连接池基本参数配置,类似数据库连接池 -->
   <context:property-placeholder location="classpath*:redis.properties" />
  <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="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" >
    <property name="hostName" value="${redis.host}"></property>
    <property name="port" value="${redis.port}"></property>
    <property name="password" value="${redis.pass}"></property>
    <property name="poolConfig" ref="poolConfig"></property> 
  </bean> -->
  <!-- 调用连接池工厂配置 -->
  <!-- <bean id="redisTemplate" class=" org.springframework.data.redis.core.RedisTemplate">
    <property name="jedisConnectionFactory" ref="jedisConnectionFactory"></property>
    如果不配置Serializer,那么存储的时候智能使用String,如果用User类型存储,那么会提示错误User can't cast to String!!! 
     <property name="keySerializer"> 
      <bean 
      class="org.springframework.data.redis.serializer.StringRedisSerializer" /> 
    </property> 
    <property name="valueSerializer"> 
      <bean 
        class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" /> 
    </property> 
  </bean> -->
   <bean id="jedisCluster" class="com.cjl.util.JedisClusterFactory">
    <property name="addressConfig">
      <value>classpath:redis.properties</value>
    </property>
    <property name="addressKeyPrefix" value="cluster" />
    <property name="timeout" value="300000" />
    <property name="maxRedirections" value="6" />
    <property name="genericObjectPoolConfig" ref="genericObjectPoolConfig" />
  </bean>
</beans>

冠亚体育手机网站 9

将上篇SSM+redis整合中mybatis的开启缓存配置全部禁用,即可启动服务测试了

要使mybaits缓存生效,还需如上图这样开启二级缓存。配置文件还需要在web.xml中加载生效

首先直接注入jedisCluster获取一个集群对象。

冠亚体育手机网站 10

冠亚体育手机网站 11

一切准备就绪后,启动服务

这里为了方便,我数据同步直接用了java写了个简单思想,其他方法也可实现,例如Spring
AOP方式实现,使用第三方插件,或者数据库层面实现都可行。

冠亚体育手机网站 12

冠亚体育手机网站 13

启动成功后,点击员工表单可以触发查询所有员工的方法,第一次进行查询语句可以看到mybatis打印了查询语句,并在redis服务器中更新了一条缓存

启动成功后,反复调用方法。可以看到控制台并未打印sql语句,而是直接在redis集群中直接获取得到数据。以上简单的redis集群实例已经完成,因为时间关系,其中linux中有些坑我没有细细写出。

冠亚体育手机网站 14

总结

冠亚体育手机网站 15

以上所述是小编给大家介绍的Redis集群与SSM整合使用方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

我们清空控制台再次点击查询员工按钮执行查询方法,可以看到没有执行查询语句,证明第二次查询直接从缓存中取值,没有连接mysql进行查询。

您可能感兴趣的文章:

  • redis与ssm整合方法(mybatis二级缓存)

冠亚体育手机网站 16

总结

以上所述是小编给大家介绍的redis与ssm整合方法(mybatis二级缓存),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

您可能感兴趣的文章:

  • Redis集群与SSM整合使用方法

Post Author: admin

发表评论

电子邮件地址不会被公开。 必填项已用*标注