前言
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