spring-data-redis读写分离

   在对Redis进行性能优化时,一直想对Redis进行读写分离。但由于项目底层采用spring-data-redis对redis进行操作,参考spring官网却发现spring-data-redis目前(1.7.0.RELEASE)及以前的版本并不支持读写分离。

 一、源码分析

  spring-data-redis中关于JedisConnectionFactory的配置如下:

<?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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">
        
    <bean id="redisSentinelConfiguration" class="org.springframework.data.redis.connection.RedisSentinelConfiguration">
        <property name="master">
            <bean class="org.springframework.data.redis.connection.RedisNode">
                <property name="name" value="mymaster"/>
                <constructor-arg name="host" value="${redis.master.host}"></constructor-arg>
                <constructor-arg name="port" value="${redis.master.port}"></constructor-arg>
            </bean>
        </property>
        <property name="sentinels">
            <set>
                <bean class="org.springframework.data.redis.connection.RedisNode">
                    <constructor-arg name="host" value="${redis.sentinel1.host}"></constructor-arg>
                    <constructor-arg name="port" value="${redis.sentinel1.port}"></constructor-arg>
                </bean>
                <bean class="org.springframework.data.redis.connection.RedisNode">
                    <constructor-arg name="host" value="${redis.sentinel2.host}"></constructor-arg>
                    <constructor-arg name="port" value="${redis.sentinel2.port}"></constructor-arg>
                </bean>
                <bean class="org.springframework.data.redis.connection.RedisNode">
                    <constructor-arg name="host" value="${redis.sentinel3.host}"></constructor-arg>
                    <constructor-arg name="port" value="${redis.sentinel3.port}"></constructor-arg>
                </bean>
            </set>
        </property>
    </bean>
    
    <!-- 连接池配置 -->
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxTotal" value="${redis.pool.maxActive}" />
        <property name="maxIdle" value="${redis.pool.maxIdle}" />
        <!-- <property name="maxWait" value="${redis.pool.maxWait}" /> -->
        <property name="testOnBorrow" value="${redis.pool.testOnBorrow}" />
        <property name="testOnReturn" value="${redis.pool.testOnReturn}" />
    </bean>
    
    <bean id="jedisConnectionFactory"
          class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="poolConfig" ref="jedisPoolConfig"></property>  
        <constructor-arg ref="redisSentinelConfiguration"/>
    </bean>

    <bean id="stringRedisTemplate" 
          class="org.springframework.data.redis.core.StringRedisTemplate" 
          p:connection-factory-ref="jedisConnectionFactory"/>
</beans>
View Code

  查看JedisConnectionFactory源码发现pool是Pool<Jedis>,而不是Pool<ShardedJedis>。因此我猜目前spring data redis是做不了读写分离的,stringRedisTemplate读写操作都是在master上。

二、读写分离改造

  参考sentinel的主备选举机制对spring-data-redis的相关配置进行如下改造:

  读写分离原理如下所示:

 

 (1)Spring配置

<?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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">
        
       <context:property-placeholder  location="classpath:redis/redis.properties" ignore-unresolvable="true" />
       
       <bean id="poolConfig" class="redis.client.jedis.JedisPoolConfig">
            <property name="maxIdle" value="${redis.maxIdle}" />
            <property name="maxTotal" value="${redis.maxTotal}" />
            <property name="maxWaitMillis" value="${redis.maxWait}" />
            <property name="testOnBuorrow" value="${redis.testOnBorrow}" />
        </bean>

    <bean id="redisSentinelConfiguration" class="org.springframework.data.redis.connection.RedisSentinelConfiguration">
     <constructor-arg index="0">
          <bean class="org.springframework.core.env.MapPropertySource">
            <constructor-arg index="0" value="RedisSentinelConffiguration" />
            <constructor-arg index="1">
               <map>
                <entry key="spring.redis.sentinel.master" value="${redis.sentinel.master}"></entry>
                <entry key="spring.redis.sentinel.nodes" value="${redis.sentinel.nodes"}> </entry>
                </map>
             </constructor-arg>
             </bean>
            </constructor-arg>
    </bean>
    
    <bean id="connectionFactory" class="com.test.data.redis.connection.TWJedisConnectionFactory">
       <constructor-arg index="0" ref="redisSentinelConfiguration" />
       <constructor-arg index="1" ref="poolConfig" />
       <property name="password" value="${redis.pass}" />
       <property name="databse" value="7" />
    </bean>
     
    <bean id="readOnlyConnectionFactory" class="com.test.data.redis.connection.TWReadOnlyJedisConnectionFactory">
       <constructor-arg index="0" ref="redisSentinelConfiguration" />
       <constructor-arg index="1" ref="poolConfig" />
       <property name="password" value="${redis.pass}" />
       <property name="databse" value="7" />
    </bean>
    

    <bean id="redisTemplate" class="com.test.data.redis.core.TWRedisTemplate" 
       <property name="connectionFactory" ref="connectionFactory"/>
       <property name="readOnlyConnectionFactory" ref="readOnlyConnectionFactory" />
     </bean>
</beans>
View Code

 (2)TWJedisConnectionFactory

public class TWJedisConnectionFactory extends JedisConnectionFactory {
 
  public TWJedisConnectionFactory() {
     super();
  }
  
  public TWJedisConnectionFactory(JedisShardInfo shardInfo) {
     super(shardInfo);
  }

  public TWJedisConnectionFactory(JedisPoolConfig poolConfig){
     this((RedisSentinelConfiguration)null,poolConfig);
  }
  
  public TWJedisConnectionFactory(RedisSentinelConfiguration sentinelConfig){
     this(sentinelConfig,null);
  }
 
  public TWJedisConnectionFactory(RedisSentinelConfiguration sentinelConfig,JedisPoolConfig poolConfig){
     super(sentinelConfig,poolConfig);
  }

  public TWJedisConnectionFactory(RedisClusterConfiguration clusterConfig){
     super(clusterConfig);
  }
  
  public TWJedisConnectionFactory(RedisClusterConfiguration clusterConfig,JedisPoolConfig poolConfig){
     super(clusterConfig,poolConfig);
  }

  @Override
  public void afterPropertiesSet() {
   try {
    super.afterPropertiesSet();
   }catch(Exception e) {
   }
  }
}
View Code

 (3)TWReadOnlyJedisConnectionFactory

public class TWReadOnlyJedisConnectionFactory extends JedisConnectionFactory {

  private static final Method GET_TIMEOUT_METHOD;

  static {
     Method getTimeoutMethodCandidate = ReflectionUtils.findMethod(JedisShardInfo.class,"getTimeout");
     if(null == getTimeoutMethodCandidate) {
       getTimeoutMethodCandidate = ReflectionUtils.findMethod(JedisShardInfo.class,"getTimeout");
     }
     GET_TIMEOUT_METHOD=getTimeoutMethodCandidate;
  }
 
  public TWReadOnlyJedisConnectionFactory() {
     super();
  }
  
  public TWReadOnlyJedisConnectionFactory(JedisShardInfo shardInfo) {
     super(shardInfo);
  }

  public TWReadOnlyJedisConnectionFactory(JedisPoolConfig poolConfig){
     this((RedisSentinelConfiguration)null,poolConfig);
  }
  
  public TWReadOnlyJedisConnectionFactory(RedisSentinelConfiguration sentinelConfig){
     this(sentinelConfig,null);
  }
 
  public TWReadOnlyJedisConnectionFactory(RedisSentinelConfiguration sentinelConfig,JedisPoolConfig poolConfig){
     super(sentinelConfig,poolConfig);
  }

  public TWReadOnlyJedisConnectionFactory(RedisClusterConfiguration clusterConfig){
     super(clusterConfig);
  }
  
  public TWJedisConnectionFactory(RedisClusterConfiguration clusterConfig,JedisPoolConfig poolConfig){
     super(clusterConfig,poolConfig);
  }

  @Override
  public void afterPropertiesSet() {
   try {
    super.afterPropertiesSet();
   }catch(Exception e) {
   }  
  }

  protected Pool<Jedis> createRedisSentinelPool(RedisSentinelConfiguration config){
    return new JedisSentinelSlavePool(config.getMaster().getName(),
           convertToJedisSentinelSet(config.getSentinels()),
           getPoolConfig()!=null?getPoolConfig():new JedisPoolConfig(),
           getTimeOutFrom(getShardInfo()),
           getShardInfo().getPassword());
  }

 private Set<String> convertToJedisSentinelSet(Collection<RedisNode> nodes) {
  if(CollectionUtils.isEmpty(nodes)) {
    return Collections.emptySet();
  }
  Set<String> convertedNodes = new LinkedHashSet<String>(nodes.size());
  for(RedisNode node : nodes)
   {
     convertedNodes.add(node.asString());
   }
  return convertedNodes;
 }
 
 private int getTimeOutFrom(JedisShardInfo shardInfo){
  return (Integer) ReflectionUtils.invokeMethod(GET_TIMEOUT_METHOD,shardInfo);
 }

}
View Code

 (4)TWRedisTemplate

public class TWRedisTemplate extends RedisTemplate {
  public static enum Operation {read,write};
  
  private static ThreadLocal<Operation> threadLocal = new ThreadLocal<TWRedisTemplate.Operation>();
  
  private RedisConnectionFactory readOnlyConnectionFactory;  
  
  public void setReadOnlyConnectionFactory(RedisConnectionFactory readOnlyConnectionFactory) {
    this.readOnlyConnectionFactory = readOnlyConnectionFactory;
  }

  public TWRedisTemplate() {
  }

  @Override
  public void afterPropertiesSet() {
   try {
    super.afterPropertiesSet();
   }catch(Exception e) {
   }  
  }

  public RedisConnectionFactory getConnectionFactory() {
    Operation operation = threadLocal.get();
    if(operation!=null && operation==Operation.read && readOnlyConnectionFactory!=null) {
      return readOnlyConnectionFactory;
    }
    return super.getConnectionFactory();
  }

 public void setOperation(Operation operation) {
   threadLocal.set(operation);
 }
}
View Code

 (5)JedisReadOnlyPool

public class JedisReadOnlyPool extends Pool<Jedis> {
  protected GenericObjectPoolConfig poolConfig;
  protected int connectionTimeout = Protocol.DEFAULT_TIMEOUT;
  protected int soTimeout = Protocol.DEFAULT_TIMEOUT;
  protected String password;
  protected int database = Protocol.DEFAULT_TIMEOUT;
  private volatile JedisFactory factory;
  private volatile HostAndPort currentHostMaster;
  
  public JedisReadOnlyPool(final HostAndPort master, final GenericObjectPoolConfig poolConfig,
                           final int connectionTimeOut, final int soTimeout, final String password, final int databse,
                           final String clientName) {
         this.poolConfig = poolConfig;
         this.connectionTimeout = connectionTimeout;
         this.soTimeout = soTimeout;
         this.password = password;
         this.database = database;
         initPool(master);
  }
  public void destory() {
   super.destroy();
  }
  
  public void initPool(HostAndPort master) {
    if(!master.equals(currentHostMaster) {
       currentHostMaster = master;
       if(factory == null) {
         factory = new JedisFactory(currentHostMaster.getHost(),
                                    currentHostMaster.getPort(),
                                    connectionTimeout,
                                    soTimeout,
                                    password,
                                    database,
                                    null);
        initPool(poolConfig,factory);
    } else {
        factory.setHostAndPort(currentHostMaster);
        internalPool.clear();
    }
    log.info("Created JedisPool to master at" + master);
   }
  }

 private HostAndPort toHostAndPort(List<String> getMasterAddByNameResult) {
   String host = getMasterAddrByNameResult.get(0);
   int port = Integer.parseInt(getMasterAddrByNameResult.get(1));
   return new HostAndPort(host,port);
 }

 @Override
 public Jedis getResource() {
   while(true) {
      Jedis jedis = super.getResource();
      jedis.setDataSource(this);
      final HostAndPort connection = new HostAndPort(jedis.getClient().getHost(),jedis.getClient().getPort());
      if(currentHostMaster.equals(connection)) {
        return jedis;
      } else {
        returnBrokenResource(jedis);
      }
   }
 }
 
 @Override
 @Deprecated
 public void returnBrokenResource(final Jedis resource) {
   if(resource!=null) {
     returnBrokenResourceObject(resource);
   }
 }

 @Override
 @Deprecated
 public void returnResource(final Jedis resource) {
  if(resource !=null ){
   resource.resetState();
   returnResourceObject(resource);
  }
 }
 
}
View Code

(6)JedisSentinelSlavesPool

(7)RedisCacheService

  在具体使用缓存服务时,在读、写缓存时分别加上其类型

...
@Autowired
private TWRedisTemplate twRedisTemplate;


public List<String> getCachedByPredis(final String prefix) {
  twRedisTemplate.setOperation(Operation.read);
  ...
  finally {
    destory();
  }
}

public void hset(xxx) {
  twRedisTemplate.setOperation(Operation.write);
  ...
  finally {
    destory();
  }
  
}


/**释放资源**/
private void destroy() {
  twRedisTemplate.setOperation(null);
}
View Code
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 要使用Redis实现Spring Boot应用程序的会话共享,您需要执行以下步骤: 1. 添加Redis依赖项 在您的Spring Boot项目中添加spring-boot-starter-data-redis依赖项,这将为您提供Redis客户端和Spring Session依赖项。 2. 配置Redis 在application.properties文件中添加Redis配置,包括Redis服务器的主机名、端口和密码。 3. 启用Spring Session 在Spring Boot应用程序中启用Spring Session,您需要将@EnabaleRedisHttpSession注释添加到Spring Boot主应用程序类上。 4. 配置会话超时 您可以在application.properties文件中设置会话超时时间,例如:spring.session.timeout=30m。 5. 测试 最后,您可以测试您的Spring Boot应用程序是否正在使用Redis进行会话共享,通过多个实例运行应用程序,并在每个实例中访问同一URL并查看结果是否相同。 通过这些步骤,您应该能够在Spring Boot应用程序中使用Redis进行会话共享。 ### 回答2: 在Spring Boot中使用Redis实现session共享可以通过以下步骤实现: 1. 首先,确保在pom.xml文件中添加以下依赖项以在Spring Boot中使用Redis: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 在application.properties文件中配置Redis连接信息: ```properties spring.redis.host=your-redis-host spring.redis.port=your-redis-port spring.redis.password=your-redis-password ``` 3. 创建一个配置类(如RedisConfig.java),用于配置与Redis的连接以及序列化的设置: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; @Configuration @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400) // 设置session的有效时间,单位为秒 public class RedisConfig { @Bean public RedisSerializer<Object> redisSerializer() { // 使用JSON序列化器,存储到Redis中的Session以JSON格式保存,方便阅 return new GenericJackson2JsonRedisSerializer(); } @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); // 设置key和value的序列化器 template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(redisSerializer()); template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(redisSerializer()); return template; } } ``` 4. 在需要使用session的地方注入`HttpSession`,并使用它来获取、设置和删除session中的属性: ```java import javax.servlet.http.HttpSession; // 注入HttpSession @Autowired private HttpSession session; // 获取session中的属性 Object attributeValue = session.getAttribute("attributeName"); // 设置session中的属性 session.setAttribute("attributeName", attributeValue); // 删除session中的属性 session.removeAttribute("attributeName"); ``` 这样,通过以上步骤,就可以在Spring Boot中使用Redis实现session共享了。注意,由于Redis是内存数据库,需要设置session的有效时间以避免占用过多的内存资源。 ### 回答3: 使用Spring Boot实现Session共享的方法有两种:使用Spring Session和使用RedisTemplate。 第一种方法是使用Spring Session来实现Session共享。Spring Session是一个用于在分布式环境下管理Session的Spring项目,它提供了一种基于Spring的Session管理解决方案。要使用Spring Session,需要在pom.xml文件中添加相关依赖,然后在Spring Boot配置类中加上@EnableRedisHttpSession注解,配置Redis连接信息。这样,Spring Session会将Session信息存储到Redis中,实现了Session的共享。 第二种方法是使用RedisTemplate来实现Session共享。RedisTemplate是Spring Data Redis提供的一个用于操作Redis的模板类,可以方便地进行Redis的操作。要使用RedisTemplate实现Session共享,首先需要在pom.xml文件中添加相关依赖,然后在Spring Boot配置类中创建一个RedisConnectionFactory实例,并将其注入到RedisTemplate中。通过RedisTemplate,可以将Session信息存储到Redis中,并实现Session的共享。 无论是使用Spring Session还是使用RedisTemplate,都需要在Spring Boot配置文件中配置Redis连接信息,包括Redis服务器的IP地址、端口号和密码(如果有)。此外,还可以配置Redis的连接池参数,以提高性能和并发能力。 总结起来,要使用Spring Boot实现Redis的Session共享,可以使用Spring Session或RedisTemplate两种方式。通过配置相关依赖和连接信息,将Session信息存储到Redis中,实现Session的共享。这样,在分布式环境下,不同的应用实例之间就能够共享Session,并实现会话的跨应用访问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值