好得很程序员自学网

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

spring-data-redis 2.0 的使用示例代码

在使用 spring boot2.x运行 redis 时,发现百度不到顺手的文档,搞通后发现其实这个过程非常简单和简洁,觉得有必要拿出来分享一下。

spring boot2.x 不再使用jedis,换成了lettuce。lettuce是基于 netty 实现的,所以性能更好。但是我看到很多文章居然在spring boot 2.x还在写jedis的配置。

依赖

依赖比较简单,spring-boot-starter- data -redis、commons-pool2 即可。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

<!-- redis -->

<dependency>

   <groupid>org.springframework.boot</groupid>

   <artifactid>spring-boot-starter-data-redis</artifactid>

</dependency>

 

 

<!--spring2. 0 集成redis所需common-pool2-->

<dependency>

   <groupid>org.apache测试数据mons</groupid>

   <artifactid>commons-pool2</artifactid>

   <version> 2.4 . 2 </version>

</dependency>

属性配置

在属性中配置redis server的访问地址、密码、数据库,并配置连接池的属性。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

redis:

  #  reids的连接ip

  host: 127.0 . 0.1

  port: 6379

  password: helloworld

 

  # redis默认情况下有 16 个分片,这里配置具体使用的分片,默认是 0

  database: 0

 

  # 连接超时时间(毫秒)

  timeout: 10000ms

 

  # redis client配置,使用lettuce

  lettuce:

   pool:

    # 连接池中的最小空闲连接 默认 0

    min-idle: 0

    # 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 - 1

    max-wait: 1000ms

    # 连接池最大连接数(使用负值表示没有限制) 默认 8

    max-active: 8

    # 连接池中的最大空闲连接 默认 8

    max-idle: 8

注解配置

全局使能缓存

?

1

2

3

4

5

6

7

8

9

@enableswagger2      // 使用swagger api 功能

@enablecaching       // 使用缓存

@springbootapplication

public class starter {

 

   public static void main(string[] args) {

     springapplication.run(starter. class , args);

   }

}

通过注解使用缓存,@cacheable 将获取值存入缓存

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

/**

  * 基于id 获取用户信息

  */

@cacheable (value= "user" , key= "#id" , unless= "#result == null" )

public userdto getuserbyid( int id) {

   user userentity = usermapper.getuserbyid(id);

   if (userentity == null ){

     return null ;

   }

 

   /* entity 转 dto */

   userdto userdto = new userdto();

   userdto.setage(userentity.getage());

   userdto.setid(id);

   userdto.setname(userentity.getname());

   userdto.setcreatetime(unixtime2string(userentity.getcreatetime()));

   userdto.setphone(userentity.getphone());

   userdto.setemail(userentity.getemail());

   return userdto;

}

@cacheput 更新缓存

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

@cacheput (value = "user" , key= "#p0.id" )

public userdto updateuser(inputuserinfodto inputuserinfodto){

   usermapper.updateuser(inputuserinfodto.getid(), inputuserinfodto.getname(), inputuserinfodto.getage());

   user userentity = usermapper.getuserbyid(inputuserinfodto.getid()); /* entity 转 dto */

 

   if ( null == userentity){

     return null ;

   }

   userdto userdto = new userdto();

   userdto.setage(userentity.getage());

   userdto.setid(userentity.getid());

   userdto.setname(userentity.getname());

   userdto.setcreatetime(unixtime2string(userentity.getcreatetime()));

   userdto.setphone(userentity.getphone());

   userdto.setemail(userentity.getemail());

   return userdto;

}

@cacheevict 删除缓存

?

1

2

3

4

@cacheevict (value = "user" , key= "#id" )

public void deleteuser( int id){

   usermapper.deleteuser(id);

}

当然为了支持序列化,我的userdto得implements serializable

?

1

2

3

4

5

6

7

8

9

10

@data

public class userdto implements serializable {

//public class userdto implements serializable {

   private int id;

   private string name;

   private int age;

   private string createtime;

   private string phone;

   private string email;

}

至此缓存已经可以用起来了,不需要编写redisconfig代码,有点小遗憾,直接去redis查看数据,发现是乱码。这是因为我使用的是java自带的序列化,如果要更换redis序列化方法,就要重写redisconfig了。

redisconfig

这个配置也不复杂,使用jackson2jsonredisserializer将对象转换为json串,注意这里一定要使用objectmapper,否则再将json串反序列化为对象时会报。

?

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

@configuration

@conditionalonclass (redisoperations. class )

@enableconfigurationproperties (redisproperties. class )

public class redisconfig extends cachingconfigurersupport{

 

   @bean

   public cachemanager cachemanager(redisconnectionfactory factory) {

     redisserializer<string> redisserializer = new stringredisserializer();

     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);

 

     // 配置序列化(解决乱码的问题)

     rediscacheconfiguration config = rediscacheconfiguration.defaultcacheconfig()

                       .entryttl(duration.zero)

                       .serializekeyswith(redisserializationcontext.serializationpair.fromserializer(redisserializer))

                       .serializevalueswith(redisserializationcontext.serializationpair.fromserializer(jackson2jsonredisserializer))

                       .disablecachingnullvalues();

 

     rediscachemanager cachemanager = rediscachemanager.builder(factory).cachedefaults(config).build();

     return cachemanager;

   }

}

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

原文链接:https://segmentfault测试数据/a/1190000017953598

查看更多关于spring-data-redis 2.0 的使用示例代码的详细内容...

  阅读:9次