好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

spring整合redis实现数据缓存的实例代码

数据缓存原因:有些数据比较多,如果每次访问都要进行查询,无疑给数据库带来太大的负担,将一些庞大的查询数据并且更新次数较少的数据存入redis,能为系统的性能带来良好的提升。

业务逻辑思路:登入系统,访问数据时,检查redis是否有缓存,有则直接从redis中提取,没有则从数据库查询出,并存入redis中做缓存。

为什么要用redis做缓存:

(1)异常快速:redis的速度非常快,每秒能执行约11万集合,每秒约81000+条记录。
(2)支持丰富的数据类型:redis支持最大多数开发人员已经知道像列表,集合,有序集合,散列数据类型。这使得它非常容易解决各种各样的问题,因为我们知道哪些问题是可以处理通过它的数据类型更好。
(3)操作都是原子性:所有redis操作是原子的,这保证了如果两个客户端同时访问的redis服务器将获得更新后的值。
(4)多功能实用工具:redis是一个多实用的工具,可以在多个用例如缓存,消息,队列使用(redis原生支持发布/订阅),任何短暂的数据,应用程序,如web应用程序会话,网页命中计数等。

缓存实现思路:

项目中配置好redis账户等属性文件(redis.properties) 整合到spring容器中(application-redis.xml) 编写redis工具类

一、项目中配置好redis账户等属性文件(redis.properties)

?

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

#ip地址

redis.hostname=youripaddress

#端口号

redis.port= 6379

#如果有密码

redis.password=yourredispassword

#客户端超时时间单位是毫秒 默认是 2000

redis.timeout= 10000

#最大空闲数

redis.maxidle= 300

#连接池的最大数据库连接数。设为 0 表示无限制,如果是jedis 2.4 以后用redis.maxtotal

#redis.maxactive= 600

#控制一个pool可分配多少个jedis实例,用来替换上面的redis.maxactive,如果是jedis 2.4 以后用该属性

redis.maxtotal= 1000

#最大建立连接等待时间。如果超过此时间将接到异常。设为- 1 表示无限制。

redis.maxwaitmillis= 1000

#连接的最小空闲时间 默认 1800000 毫秒( 30 分钟)

redis.minevictableidletimemillis= 300000

#每次释放连接的最大数目,默认 3

redis.numtestsperevictionrun= 1024

#逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认- 1

redis.timebetweenevictionrunsmillis= 30000

#是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个

redis.testonborrow= true

#在空闲时检查有效性, 默认 false

redis.testwhileidle= true

二、整合到spring容器中(application-redis.xml)

 

?

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

<?xml version= "1.0" encoding= "utf-8" ?>

<beans xmlns= "http://HdhCmsTestspringframework.org/schema/beans"

   xmlns:xsi= "http://HdhCmsTestw3.org/2001/xmlschema-instance" xmlns:p= "http://HdhCmsTestspringframework.org/schema/p"

   xmlns:context= "http://HdhCmsTestspringframework.org/schema/context"

   xmlns:mvc= "http://HdhCmsTestspringframework.org/schema/mvc"

   xmlns:cache= "http://HdhCmsTestspringframework.org/schema/cache"

   xmlns:aop= "http://HdhCmsTestspringframework.org/schema/aop"

   xsi:schemalocation="http: //HdhCmsTestspringframework.org/schema/beans  

             http: //HdhCmsTestspringframework.org/schema/beans/spring-beans.xsd  

             http: //HdhCmsTestspringframework.org/schema/context  

             http: //HdhCmsTestspringframework.org/schema/context/spring-context.xsd  

             http: //HdhCmsTestspringframework.org/schema/mvc  

             http: //HdhCmsTestspringframework.org/schema/mvc/spring-mvc.xsd

             http: //HdhCmsTestspringframework.org/schema/cache 

             http: //HdhCmsTestspringframework.org/schema/cache/spring-cache.xsd

             http: //HdhCmsTestspringframework.org/schema/aop 

             http: //HdhCmsTestspringframework.org/schema/aop/spring-aop.xsd">

   <!-- 加载配置文件 -->

   <context:property-placeholder ignore-unresolvable= "true" location= "classpath:properties/redis.properties" />

   <!-- redis连接池配置-->

   <bean id= "jedispoolconfig" class = "redis.clients.jedis.jedispoolconfig" >

     <!--最大空闲数-->

     <property name= "maxidle" value= "${redis.maxidle}" />

     <!--连接池的最大数据库连接数 -->

     <property name= "maxtotal" value= "${redis.maxtotal}" />

     <!--最大建立连接等待时间-->

     <property name= "maxwaitmillis" value= "${redis.maxwaitmillis}" />

     <!--逐出连接的最小空闲时间 默认 1800000 毫秒( 30 分钟)-->

     <property name= "minevictableidletimemillis" value= "${redis.minevictableidletimemillis}" />

     <!--每次逐出检查时 逐出的最大数目 如果为负数就是 : 1 /abs(n), 默认 3 -->

     <property name= "numtestsperevictionrun" value= "${redis.numtestsperevictionrun}" />

     <!--逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认- 1 -->

     <property name= "timebetweenevictionrunsmillis" value= "${redis.timebetweenevictionrunsmillis}" />

     <!--是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个-->

     <property name= "testonborrow" value= "${redis.testonborrow}" />

     <!--在空闲时检查有效性, 默认 false -->

     <property name= "testwhileidle" value= "${redis.testwhileidle}" />

   </bean >

   <!--redis连接工厂 -->

   <bean id= "jedisconnectionfactory" class = "org.springframework.data.redis.connection.jedis.jedisconnectionfactory" destroy-method= "destroy" >

     <property name= "poolconfig" ref= "jedispoolconfig" ></property>

     <!--ip地址 -->

     <property name= "hostname" value= "${redis.hostname}" ></property>

     <!--端口号 -->

     <property name= "port" value= "${redis.port}" ></property>

     <!--如果redis设置有密码 -->

     <property name= "password" value= "${redis.password}" />

     <!--客户端超时时间单位是毫秒 -->

     <property name= "timeout" value= "${redis.timeout}" ></property>

   </bean>

   <!--redis操作模版,使用该对象可以操作redis -->

   <bean id= "redistemplate" class = "org.springframework.data.redis.core.redistemplate" >

     <property name= "connectionfactory" ref= "jedisconnectionfactory" />

     <!--如果不配置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.genericjackson2jsonredisserializer" />

     </property>

     <property name= "hashkeyserializer" >

       <bean class = "org.springframework.data.redis.serializer.stringredisserializer" />

     </property>

     <property name= "hashvalueserializer" >

       <bean class = "org.springframework.data.redis.serializer.genericjackson2jsonredisserializer" />

     </property>

     <!--开启事务 -->

     <property name= "enabletransactionsupport" value= "true" ></property>

   </bean >

   <!--自定义redis工具类,在需要缓存的地方注入此类 -->

   <bean id= "redisutil" class = "com.neuedu.crm.utils.redisutil" >

     <property name= "redistemplate" ref= "redistemplate" />

   </bean>

</beans>

三、编写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

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

package com.neuedu.crm.utils;

import java.io.serializable;

import java.util.set;

import java.util.concurrent.timeunit;

import org.slf4j.logger;

import org.slf4j.loggerfactory;

import org.springframework.data.redis.core.redistemplate;

import org.springframework.data.redis.core.valueoperations;

/**

  * redis工具类

  * :用于缓存数据

  *

  */

public class redisutil {

   private logger logger = loggerfactory.getlogger(redisutil. class );

   private redistemplate<serializable, object> redistemplate;

   public void setredistemplate(redistemplate<serializable, object> redistemplate) {

     this .redistemplate = redistemplate;

   }

   /**

    * 批量删除对应的value

    *

    * @param keys

    */

   public void remove( final string... keys) {

     for (string key : keys) {

       remove(key);

     }

   }

   /**

    * 批量删除key

    *

    * @param pattern

    */

   public void removepattern( final string pattern) {

     set<serializable> keys = redistemplate.keys(pattern);

     if (keys.size() > 0 ) {

       redistemplate.delete(keys);

     }

   }

   /**

    * 删除对应的value

    *

    * @param key

    */

   public void remove( final string key) {

     logger.info( "要移除的key为:" + key);

     if (exists(key)) {

       redistemplate.delete(key);

     }

   }

   /**

    * 判断缓存中是否有对应的value

    *

    * @param key

    * @return

    */

   public boolean exists( final string key) {

     logger.info( "要验证是否存在的key为:" + key);

     return redistemplate.haskey(key);

   }

   /**

    * 读取缓存

    *

    * @param key

    * @return

    */

   public object get( final string key) {

     object result = null ;

     valueoperations<serializable, object> operations = redistemplate

         .opsforvalue();

     result = operations.get(key);

     return result;

   }

   /**

    * 写入缓存

    *

    * @param key

    * @param value

    * @return

    */

   public boolean set( final string key, object value) {

     boolean result = false ;

     try {

       valueoperations<serializable, object> operations = redistemplate

           .opsforvalue();

       operations.set(key, value);

       result = true ;

     } catch (exception e) {

       logger.error( "系统异常" ,e);

     }

     return result;

   }

   /**

    * 写入缓存

    *

    * @param key

    * @param value

    * @return

    */

   public boolean set( final string key, object value, long expiretime) {

     boolean result = false ;

     try {

       valueoperations<serializable, object> operations = redistemplate

           .opsforvalue();

       operations.set(key, value);

       redistemplate.expire(key, expiretime, timeunit.seconds);

       result = true ;

     } catch (exception e) {

       logger.error( "系统异常" ,e);

     }

     return result;

   }

}

注意点:redis工具类由spring进行托管,则在需要缓存的地方注入redis工具类即可。

总结

以上所述是小编给大家介绍的spring整合redis实现数据缓存的实例代码,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

原文链接:https://blog.csdn.net/chenjianzhou107/article/details/82724947

查看更多关于spring整合redis实现数据缓存的实例代码的详细内容...

  阅读:24次