spring中redis怎么用


本文摘自PHP中文网,作者藏色散人,侵删。

spring中redis怎么用?

在Spring中使用Redis

Java中操作Redis使用的是Jedis,首先在pom.xml中加入相关依赖:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

<!-- redis cache related.....start -->

<dependency>

<groupId>org.springframework.data</groupId>

<artifactId>spring-data-redis</artifactId>

<version>1.6.0.RELEASE</version>

</dependency>

<dependency>

<groupId>redis.clients</groupId>

<artifactId>jedis</artifactId>

<version>2.7.3</version>

</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->

<dependency>

    <groupId>org.apache.commons</groupId>

    <artifactId>commons-pool2</artifactId>

    <version>2.4.2</version>

</dependency>

<!-- redis cache related.....end -->

然后实现配置类:

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

package com.ehelp.util;

  

import org.springframework.cache.CacheManager;

import org.springframework.cache.annotation.CachingConfigurerSupport;

import org.springframework.cache.annotation.EnableCaching;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.data.redis.cache.RedisCacheManager;

import org.springframework.data.redis.connection.RedisConnectionFactory;

import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;

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

  

@Configuration

@EnableCaching

public class RedisCacheConfig extends CachingConfigurerSupport {

  

@Bean

public JedisConnectionFactory redisConnectionactory() {

JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory();

redisConnectionFactory.setHostName("localhost");

redisConnectionFactory.setPort(6379);

return redisConnectionFactory;

}

  

@Bean

public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf) {

RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();

redisTemplate.setConnectionFactory(cf);

return redisTemplate;

}

@Bean

public CacheManager cacheManager(RedisTemplate redisTemplate) {

RedisCacheManager cacheManger = new RedisCacheManager(redisTemplate);

cacheManger.setDefaultExpiration(5); //cache过期时间

return cacheManger;

}

}

注意:

设置 Cache 过期时间要合适,太长就长期有效,太短你看不到测试结果。建议 5-20秒。

最后直接在需要添加缓存的方法上使用注解就可实现缓存:

e70e1fd4d4e6963d794a34da88a29f2.png

更多Redis相关知识,请访问Redis使用教程栏目!

以上就是spring中redis怎么用的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

redis与memcache的区别有哪些

如何保证redis中都是热点数据

redis是原子性吗

redis中的关系查询介绍

redis事件处理流程分析

探索redis持久化原理

redis在哪里配置缓存清理策略

深入浅析redis中的三种特殊数据类型

怎么理解redis

redis怎么持久化数据

更多相关阅读请进入《spring》频道 >>


数据库系统概念 第6版
书籍

数据库系统概念 第6版

机械工业出版社

本书主要讲述了数据模型、基于对象的数据库和XML、数据存储和查询、事务管理、体系结构等方面的内容。



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...