好得很程序员自学网

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

SpringBoot集成redis的示例代码

前言

redis想必小伙伴们即使没有用过,也是经常听到的,在工作中,redis用到的频率非常高,今天详细介绍一下SpringBoot中的集成步骤

一、 redis是什么

用通俗点的话解释,redis就是一个数据库,直接运行在内存中,因此其运行速度相当快,同时其并发能力也非常强。redis是以key-value键值对的形式存在(如:"name":huage),它的key有五种常见类型:

String:字符串 Hash:字典 List:列表 Set:集合 SortSet:有序集合

除此之外,redis还有一些高级数据结构,如HyperLogLog、Geo、Pub/Sub以及BloomFilter、RedisSearch等,这个后面花Gie会有专门的系列来讲解,这里不再展开啦(不然肝不完了)。

二、 集成redis步骤

pom文件配置

?

1

2

3

4

5

6

7

8

9

10

11

<!--redis-->

< dependency >

     < groupId >org.springframework.boot</ groupId >

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

</ dependency >

<!--jedis-->

< dependency >

     < groupId >redis.clients</ groupId >

     < artifactId >jedis</ artifactId >

     < version >2.9.0</ version >

</ dependency >

配置文件

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

#redis配置开始

# Redis数据库索引(默认为0)

spring.redis.database=0

# Redis服务器地址

spring.redis.host=127.0.0.1

# Redis服务器连接端口

spring.redis.port=6379

# Redis服务器连接密码(默认为空)

spring.redis.password=

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

spring.redis.jedis.pool.max-active=1024

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

spring.redis.jedis.pool.max-wait=10000

# 连接池中的最大空闲连接

spring.redis.jedis.pool.max-idle=200

# 连接池中的最小空闲连接

spring.redis.jedis.pool.min-idle=0

# 连接超时时间(毫秒)

spring.redis.timeout=10000

#redis配置结束

spring.redis.block-when-exhausted=true

初始化配置文件

?

1

2

3

4

5

6

7

8

9

10

11

12

//初始化jedis

public JedisPool redisPoolFactory() throws Exception {

     JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();

     jedisPoolConfig.setMaxIdle(maxIdle);

     jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);

     // 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true

     jedisPoolConfig.setBlockWhenExhausted(blockWhenExhausted);

     // 是否启用pool的jmx管理功能, 默认true

     jedisPoolConfig.setJmxEnabled( true );

     JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);

     return jedisPool;

}

三、 代码演示

完成上面的配置后,我们只需要使用@Autowired引入RedisTemplate,就可以很方便的存取redis了,此外花Gie在项目中增加了一个RedisUtil工具类,囊括了redis大部分命令,足够平时开发使用。

?

1

2

3

4

5

6

7

8

//引入redis

@Autowired

private RedisTemplate redisTemplate;

//将【name:花哥】 存入redis

redisTemplate.opsForValue().set( "name" , "花哥" );

//取出redis中key为name的数据

redisTemplate.opsForValue().get( "name" );

到此这篇关于SpringBoot集成redis的示例代码的文章就介绍到这了,更多相关SpringBoot集成redis内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://juejin.cn/post/7022275214641725454

查看更多关于SpringBoot集成redis的示例代码的详细内容...

  阅读:15次