服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - 详解简单基于spring的redis配置(单机和集群模式)

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

2021-07-16 15:55muistar Java教程

这篇文章主要介绍了详解简单基于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

?
1
2
3
4
5
6
<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

?
1
2
3
4
5
6
7
8
9
10
<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.配置连接池

?
1
2
3
4
5
6
7
8
9
10
<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

?
1
2
3
4
5
6
7
8
<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集群

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<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

或者

?
1
2
3
4
5
6
<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,这里只配置集群样例

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
@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那当我没说过这句话...

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

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

?
1
<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一样可能存在潜在问题啊,所以说嘛,公司有时候还是需要更新换代下吧...)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://segmentfault.com/a/1190000018208317

延伸 · 阅读

精彩推荐