spring-boot整合Redis-基于Jedis

工具:IDEA
spring boot version: 2.1.3

  1. 使用 Spring Initializr 創(chuàng)建最簡(jiǎn)單的spring-boot項(xiàng)目

不用添加任何依賴(lài),后面可以根據(jù)需要添加。

  1. 添加依賴(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>
  1. 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
  1. 啟動(dòng)本地 redis-server


    redis-server.png
  2. 測(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);
    }
}
  1. 測(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!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容