springboot+ehcache+redis集群

本文详细介绍如何在本地搭建由三个节点组成的Redis集群,并通过Spring框架进行整合,实现集群模式下的二级缓存功能。文中提供了具体的配置代码示例,包括集群配置、连接池配置以及RedisTemplate的序列化设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前面实现了二级缓存。接下来要实现redis集群模式。本地实现6380 6381 6382模拟三台redis节点组成的集群

修改大致如下:

(1)修改redis单机节点的相关配置变为集群的配置;

spring.redis.cluster.nodes=127.0.0.1:6380,127.0.0.1:6381,127.0.0.1:6382
spring.redis.cluster.timeout=1000
spring.redis.cluster.max-redirects=3
spring.redis.cluster.password=123456
#单redis服务器加载此配置
spring.redis.database = 0
#spring.redis.host=127.0.0.1
#spring.redis.port=6379
#连接超时时间
#最大活跃连接数
spring.redis.jedis.pool.max-active=10
#最大空闲连接数
spring.redis.jedis.pool.max-idle=5
#最长等待时间。-1不等待
spring.redis.jedis.pool.max-wait=-1
#最小空闲数0
spring.redis.jedis.pool.min-idle=0

(2) redis集群的相关配置:有原先单机节点配置变为集群配置使用了jedispoolconconfig

package com.example.demo.config;

import com.example.demo.po.RedisClusterProperties;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.MapPropertySource;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Configuration
public class RedisClusterConfig {


    @Value("${spring.redis.jedis.pool.max-active}")
    private String maxActive;

    @Value("${spring.redis.jedis.pool.max-idle}")
    private String maxIdle;

    @Value("${spring.redis.jedis.pool.max-wait}")
    private String maxWait;


    @Value("${spring.redis.jedis.pool.min-idle}")
    private String minIdle;


    @Autowired
    private RedisClusterProperties clusterProperties;

    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

    /**
     * redis集群配置
     * @return
     */
    @Bean
    public RedisClusterConfiguration  redisClusterConfiguration() {
        RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();
        //Set<RedisNode> clusterNodes
        String[] serverArray = clusterProperties.getNodes().split(",");
        Set<RedisNode> nodes = new HashSet<RedisNode>();
        for(String ipPort:serverArray){
            String[] ipAndPort = ipPort.split(":");
            nodes.add(new RedisNode(ipAndPort[0].trim(),Integer.valueOf(ipAndPort[1])));
        }
        redisClusterConfiguration.setClusterNodes(nodes);
        redisClusterConfiguration.setMaxRedirects(Integer.valueOf(clusterProperties.getMaxRedirects()));
        redisClusterConfiguration.setPassword(RedisPassword.of(clusterProperties.getPassword()));
        return redisClusterConfiguration;
    }

    /**
     * @param
     * @return
     * @Description:redis连接工厂类
     * @date 2018/10/25 19:45
     */
   /* @Bean
    public RedisConnectionFactory myLettuceConnectionFactory(RedisClusterConfiguration redisClusterConfiguration) {
        RedisConnectionFactory redisConnectionFactory = new LettuceConnectionFactory(redisClusterConfiguration);
        return redisConnectionFactory;
    }*/

    @Bean
    public JedisPoolConfig getJedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        // 最大空闲数
        jedisPoolConfig.setMaxIdle(Integer.valueOf(maxIdle));
        // 连接池的最大数据库连接数
        jedisPoolConfig.setMaxTotal(Integer.valueOf(maxActive));
        // 最大建立连接等待时间
        jedisPoolConfig.setMaxWaitMillis(Integer.valueOf(maxWait));
        return jedisPoolConfig;
    }

    /**
     * @param
     * @return
     * @Description:redis连接工厂类
     * @date 2018/10/25 19:45
     */
    @Bean
    public JedisConnectionFactory jedisConnectionFactory() {
        //集群模式
        JedisConnectionFactory  factory = new JedisConnectionFactory(redisClusterConfiguration(),getJedisPoolConfig());
        factory.setDatabase(0);
        factory.setTimeout(clusterProperties.getTimeout());
        factory.setUsePool(true);
        return factory;
    }





}

(3)集群启动后直接测试就行。被人亲测过。没有问题

在下图  两个节点中存储了name的信息

### 实现Spring Boot Shiro Session缓存 #### 使用Ehcache作为Session缓存机制 为了使Shiro能够利用Ehcache来存储会话数据,需先引入必要的依赖项到`pom.xml`文件中: ```xml <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring-boot-web-starter</artifactId> <version>${shiro.version}</version> </dependency> <!-- EhCache --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>${ehcache.version}</version> </dependency> ``` 接着定义一个名为`ShiroEhcacheManager.java`的Java类用于初始化Ehcache实例并将其注册给Shiro环境。 ```java import org.apache.shiro.cache.CacheManager; import org.apache.shiro.cache.ehcache.EhCacheManager; @Configuration public class ShiroEhcacheManager { @Bean(name="cacheManager") public CacheManager getCacheManager(){ EhCacheManager em = new EhCacheManager(); em.setCacheManagerConfigFile("classpath:ehcache-shiro.xml"); return em; } } ``` 上述代码片段展示了如何配置Ehcache成为默认的缓存提供者[^2]。注意这里指定了外部化的EHCache配置文件路径以便更灵活地调整缓存策略参数。 对于具体的Ehcache配置(`ehcache-shiro.xml`),可以根据实际需求定制化设置不同的缓存区域及其过期策略等特性。 --- #### 结合Redis实现分布式环境下的一致性Session管理 当应用程序部署于多节点集群架构下时,则推荐采用Redis替代本地内存或单机版Ehcache来进行跨服务器间共享同一份实时更新后的用户登录状态副本。此时除了继续保留原有的Shiro核心功能外还需要额外增加如下几处改动: 1. **添加Maven坐标** 同样编辑项目根目录下的`pom.xml`文档追加对lettuce驱动的支持以连接远程Redis服务端口监听地址; ```xml <!-- Redis Client Library --> <dependency> <groupId>io.lettuce.core</groupId> <artifactId>lettuce-core</artifactId> <version>${redis.version}</version> </dependency> <!-- Enable Spring Data Redis support --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. **编写自定义SessionDAO继承DefaultWebSessionDao** 创建一个新的子类重写其中部分方法从而允许我们将原本保存至JVM堆内的对象序列化后持久化入指定key-value store之中去。 ```java import java.io.Serializable; import javax.annotation.Resource; import org.apache.shiro.session.Session; import org.apache.shiro.session.mgt.ValidatingSession; import org.apache.shiro.session.mgt.eis.CachingSessionDAO; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.serializer.StringRedisSerializer; ... /** * Customized implementation of {@link CachingSessionDAO} that stores sessions into a distributed cache. */ public final class RedisSessionDAO extends AbstractValidatingSessionDAO implements Serializable { private static final long serialVersionUID = 793480567L; private String keyPrefix = "shiro_redis_session:"; ... protected void doUpdate(Session session){ // Update the corresponding entry within external storage system... } protected void doDelete(Session session){ // Remove expired entries from persistent layer accordingly... } protected Serializable getSessionId(Serializable sessionId, boolean create){ if (create && null == sessionId) { return generateNewSessionId(); } else { return sessionId; } } ... } ``` 3. **激活@EnableRedisHttpSession注解开关** 修改之前提到过的全局配置类使其具备感知HTTP请求上下文中携带cookie信息的能力进而完成自动续签操作防止频繁触发全量同步动作造成不必要的网络开销浪费现象发生。 ```java package com.example.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.session.data.redis.config.ConfigureRedisAction; import org.springframework.session.web.http.CookieSerializer; import org.springframework.session.web.http.DefaultCookieSerializer; @Configuration @EnableRedisHttpSession(maxInactiveIntervalInSeconds=86400*30)//maxInactiveIntervalInSeconds: 设置Session失效时间 public class SessionConfig { @Bean ConfigureRedisAction configureRedisAction() { return ConfigureRedisAction.NO_OP; } @Bean CookieSerializer cookieSerializer() { DefaultCookieSerializer serializer = new DefaultCookieSerializer(); serializer.setDomainNamePattern("^.+?\\.(\\w+\\.[a-z]+)$"); return serializer; } } ``` 以上即是在Spring Boot应用里集成Apache Shiro框架并通过第三方中间件优化其内部工作流程的一些常见实践方案[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值