当前位置: 首页 > news >正文

简单基于spring的redis配置(单机和集群模式)

需要的jar包:spring版本:4.3.6.RELEASE,jedis版本:2.9.0,spring-data-redis:1.8.0.RELEASE;如果使用jackson序列化的话还额外需要:jackson-annotations和jackson-databind包

spring集成redis单机版:
    1.配置RedisTemplate
        <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
            <property name="connectionFactory" ref="connectionFactory"/>
            <property name="defaultSerializer" ref="stringRedisSerializer"/>
            <property name="keySerializer" ref="stringRedisSerializer"/>
            <property name="valueSerializer" ref="valueSerializer"/>
        </bean>
    2.配置connectionFactory
        <bean id="connectionFactory"  class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
            <!-- 配置ip -->
            <property name="hostName" value="${redis.host}"/>
            <!-- 配置port -->
            <property name="port" value="${redis.port}"/>
            <!-- 是否使用连接池-->
            <property name="usePool" value="${redis.usePool}"/>
            <!-- 配置redis连接池-->
            <property name="poolConfig" ref="poolConfig"/>
        </bean>
   3.配置连接池
        <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
            <!--最大空闲实例数-->
            <property name="maxIdle" value="${redis.maxIdle}" />
            <!--最大活跃实例数-->
            <property name="maxTotal" value="${redis.maxTotal}" />
            <!--创建实例时最长等待时间-->
            <property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
            <!--创建实例时是否验证-->
            <property name="testOnBorrow" value="${redis.testOnBorrow}" />
        </bean>

spring集成redis集群
    1.配置RedisTemplate步骤与单机版一致
    2.配置connectionFactory
        <bean id="connectionFactory"  class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
            <!-- 配置redis连接池-->    
            <constructor-arg ref="poolConfig"></constructor-arg>
            <!-- 配置redis集群-->  
         <constructor-arg ref="clusterConfig"></constructor-arg>
            <!-- 是否使用连接池-->
            <property name="usePool" value="${redis.usePool}"/>
        </bean>
    3.配置连接池步骤与单机版一致
    4.配置redis集群
        <bean id="clusterConfig" class="org.springframework.data.redis.connection.RedisClusterConfiguration">
            <property name="maxRedirects" value="3"></property>
            <property name="clusterNodes">
                <set>
                    <bean class="org.springframework.data.redis.connection.RedisClusterNode">
                        <constructor-arg value="${redis.host1}"></constructor-arg>
                        <constructor-arg value="${redis.port1}"></constructor-arg>
                    </bean>
                    <bean class="org.springframework.data.redis.connection.RedisClusterNode">
                        <constructor-arg value="${redis.host2}"></constructor-arg>
                        <constructor-arg value="${redis.port2}"></constructor-arg>
                    </bean>
                    ......
                </set>
            </property>
        </bean>
    或者
        <bean name="propertySource" class="org.springframework.core.io.support.ResourcePropertySource">
            <constructor-arg name="location" value="classpath:properties/spring-redis-cluster.properties" />
        </bean>
        <bean id="clusterConfig" class="org.springframework.data.redis.connection.RedisClusterConfiguration">
            <constructor-arg name="propertySource" ref="propertySource"/>
        </bean>

序列化配置简述:

1.stringRedisSerializer:由于redis的key是String类型所以一般使用StringRedisSerializer
2.valueSerializer:对于redis的value序列化,spring-data-redis提供了许多序列化类,这里建议使用Jackson2JsonRedisSerializer,默认为JdkSerializationRedisSerializer
3.JdkSerializationRedisSerializer: 使用JDK提供的序列化功能。 优点是反序列化时不需要提供类型信息(class),但缺点是序列化后的结果非常庞大,是JSON格式的5倍左右,这样就会消耗redis服务器的大量内存。
4.Jackson2JsonRedisSerializer:使用Jackson库将对象序列化为JSON字符串。优点是速度快,序列化后的字符串短小精悍。但缺点也非常致命,那就是此类的构造函数中有一个类型参数,必须提供要序列化对象的类型信息(.class对象)。

使用spring注解式来配置redis,这里只配置集群样例

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    //spring3支持注解方式获取value 在application里配置配置文件路径即可获取
    @Value("${spring.redis.cluster.nodes}")
    private String clusterNodes;

    @Value("${spring.redis.cluster.timeout}")
    private Long timeout;

    @Value("${spring.redis.cluster.max-redirects}")
    private int redirects;

    @Value("${redis.maxIdle}")
    private int maxIdle;

    @Value("${redis.maxTotal}")
    private int maxTotal;

    @Value("${redis.maxWaitMillis}")
    private long maxWaitMillis;

    @Value("${redis.testOnBorrow}")
    private boolean testOnBorrow;

    /**
     * 选择redis作为默认缓存工具
     * @param redisTemplate
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        //cacheManager.setDefaultExpiration(60);
        //Map<String,Long> expiresMap=new HashMap<>();
        //expiresMap.put("redisCache",5L);
        //cacheManager.setExpires(expiresMap);
        return cacheManager;
    }

    @Bean
    public RedisClusterConfiguration redisClusterConfiguration(){
        Map<String, Object> source = new HashMap<>();
        source.put("spring.redis.cluster.nodes", clusterNodes);
        source.put("spring.redis.cluster.timeout", timeout);
        source.put("spring.redis.cluster.max-redirects", redirects);
        return new RedisClusterConfiguration(new MapPropertySource("RedisClusterConfiguration", source));
    }

    @Bean
    public JedisConnectionFactory redisConnectionFactory(RedisClusterConfiguration configuration){
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(maxIdle);
        poolConfig.setMaxTotal(maxTotal); 
        poolConfig.setMaxWaitMillis(maxWaitMillis);
        poolConfig.setTestOnBorrow(testOnBorrow);
        return new JedisConnectionFactory(configuration,poolConfig);
    }

    /**
     * retemplate相关配置
     * @param factory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory factory) {

        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(factory);

        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        //om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);

        // 值采用json序列化
        template.setValueSerializer(jacksonSeial);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());

        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
    
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();

        return template;
    }
}

注意事项:

1.采用注解式配置redis或者使用@Configuration需要在配置文件中指定扫描什么哪些包下的配置文件,当然如果是springboot那当我没说过这句话...

<context:component-scan base-package="com.*"/>

2.spring3支持注解方式获取Value,但是需要在加载的配置文件配置文件路径即可,具体值自己指定吧...

<value>classpath:properties/spring-redis-cluster.properties</value>

3.由于我们公司原有的框架采用的是spring2.5.6, 而对于spring2 和spring2+主要区别(当然是我自己觉得啊)是把各模块分成了不同的jar,而对于使用spring-data-redis模板化处理redis的话,单机情况下spring2.5.6和spring4不会冲突,而如果使用集群模式需要配置redis集群的时候就会出现jar包冲突,这个时候就看要如何取决了,可以直接使用jedisCluster来连接redis集群(不过很多方法都需要自己去写),也可以把spring2.5.6替换成高版本的spring4,只是框架替换需要注意的事情更多了啊(我们公司的直接全部替换没啥毛病好吧,O(∩_∩)O哈哈~),至于重写JedisConnectionFactory和RedisClusterConfiguration我还未去尝试,这个可以作为后续补充吧...

4.顺便说句,spring4不在支持ibatis了,如果你需要用spring4,又需要连接ibatis的话,最粗暴的方式是把spring-orm包换成spring3版本,其他的jar还是4版本即可。(当然我这边直接替换是没啥问题,但同3一样可能存在潜在问题啊,所以说嘛,公司有时候还是需要更新换代下吧...)

相关文章:

  • 关于字符编码你应该知道的事情
  • 微信小程序--------语音识别(前端自己也能玩)
  • IoC组件Unity再续~根据类型字符串动态生产对象
  • Netty+SpringBoot+FastDFS+Html5实现聊天App(六)
  • 什么是API网关 如何设计亿万级统一网关
  • React的组件模式
  • passportjs 源码分析
  • Google Play 下架 App 之后的替身制作
  • 安卓应用性能调试和优化经验分享
  • Redis 懒删除(lazy free)简史
  • vue全家桶+Koa2开发笔记(8)--开发网页
  • Mycat - 实现数据库的读写分离与高可用
  • 理解 JavaScript 中的 this
  • 块级、内联、内联块级
  • Spring Boot 运作原理
  • [笔记] php常见简单功能及函数
  • 【css3】浏览器内核及其兼容性
  • android 一些 utils
  • JavaScript实现分页效果
  • node-sass 安装卡在 node scripts/install.js 解决办法
  • Odoo domain写法及运用
  • overflow: hidden IE7无效
  • PHP那些事儿
  • React+TypeScript入门
  • select2 取值 遍历 设置默认值
  • Spring Boot MyBatis配置多种数据库
  • 多线程事务回滚
  • 驱动程序原理
  • 如何合理的规划jvm性能调优
  • 少走弯路,给Java 1~5 年程序员的建议
  • 推荐一款sublime text 3 支持JSX和es201x 代码格式化的插件
  • #define与typedef区别
  • #Spring-boot高级
  • (173)FPGA约束:单周期时序分析或默认时序分析
  • (3)选择元素——(14)接触DOM元素(Accessing DOM elements)
  • (39)STM32——FLASH闪存
  • (42)STM32——LCD显示屏实验笔记
  • (cljs/run-at (JSVM. :browser) 搭建刚好可用的开发环境!)
  • (Oracle)SQL优化技巧(一):分页查询
  • (附源码)springboot 个人网页的网站 毕业设计031623
  • (七)MySQL是如何将LRU链表的使用性能优化到极致的?
  • (算法二)滑动窗口
  • (提供数据集下载)基于大语言模型LangChain与ChatGLM3-6B本地知识库调优:数据集优化、参数调整、Prompt提示词优化实战
  • (五)Python 垃圾回收机制
  • (原创)boost.property_tree解析xml的帮助类以及中文解析问题的解决
  • (转)linux下的时间函数使用
  • .net 使用$.ajax实现从前台调用后台方法(包含静态方法和非静态方法调用)
  • .net 逐行读取大文本文件_如何使用 Java 灵活读取 Excel 内容 ?
  • .net6解除文件上传限制。Multipart body length limit 16384 exceeded
  • .NET设计模式(11):组合模式(Composite Pattern)
  • .Net中的设计模式——Factory Method模式
  • @DataRedisTest测试redis从未如此丝滑
  • [Angular 基础] - 自定义指令,深入学习 directive
  • [C#][opencvsharp]opencvsharp sift和surf特征点匹配
  • [codeforces] 25E Test || hash