工具:IDEA
spring boot version: 2.1.3
- 使用 Spring Initializr 創(chuàng)建最簡(jiǎn)單的spring-boot項(xiàng)目
不用添加任何依賴(lài),后面可以根據(jù)需要添加。
- 添加依賴(lài):
- spring-boot-redis + jedis
<!-- spring-boot集成redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<!-- 排除redis默認(rèn)客戶(hù)端lettuce -->
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 使用jedis作為redis的客戶(hù)端 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
- spring-boot-web(后面編寫(xiě)接口測(cè)試)
<!--web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
- application.properties配置redis
# redis 配置
# redis 服務(wù)器IP(默認(rèn):localhost)
spring.redis.host=localhost
# 端口號(hào)(默認(rèn):6379)
spring.redis.port=6379
# 客戶(hù)端超時(shí)時(shí)間
spring.redis.timeout=10000
# 最大空閑數(shù),使用負(fù)值表示不限數(shù)量(默認(rèn):8)
spring.redis.jedis.pool.max-idle=8
# 最大數(shù)據(jù)庫(kù)連接數(shù),使用負(fù)值表示無(wú)限制(默認(rèn):8)
spring.redis.jedis.pool.max-active=8
-
啟動(dòng)本地 redis-server
redis-server.png - 測(cè)試代碼
- RedisUtil工具類(lèi)(部分代碼)
該工具類(lèi)來(lái)自:GitHub文檔
@Component
public class RedisUtil {
@Autowired
private StringRedisTemplate redisTemplate;
/**
* 是否存在key
* @param key
* @return
*/
public Boolean hasKey(String key) {
return redisTemplate.hasKey(key);
}
/**
* 設(shè)置指定 key 的值
* @param key
* @param value
*/
public void set(String key, String value) {
redisTemplate.opsForValue().set(key, value);
}
/**
* 獲取指定 key 的值
* @param key
* @return
*/
public String get(String key) {
return redisTemplate.opsForValue().get(key);
}
// 其他方法省略
}
- 測(cè)試接口代碼
@RestController
public class RedisTestController {
@Autowired
private RedisUtil redisUtil;
@RequestMapping("/key")
public String getKey(String key){
if(!redisUtil.hasKey(key)){
redisUtil.set(key, "bearPotMan");
}
return redisUtil.get(key);
}
}
- 測(cè)試結(jié)果
redis-test-result.png
結(jié)束語(yǔ):沒(méi)有過(guò)多理論性的知識(shí)或原理的講解,只是從一個(gè)普通開(kāi)發(fā)的角度來(lái)使用。
我是bearPotMan,一個(gè)經(jīng)驗(yàn)不足的十八線演(碼)員(農(nóng))。
Know everything,control everything!

