国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Spring Boot 中使用 Redis

這篇具有很好參考價值的文章主要介紹了Spring Boot 中使用 Redis。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

Redis 環(huán)境

redis 安裝、配置,啟動:(此處以云服務器上進行說明)

下載地址:https://redis.io/download/
下載后上傳到云服務器上,如 /usr/local 中

gcc 環(huán)境安裝:yum install -y gcc-c++

解壓:tar -zxvf xxx

進入解壓后的 redis 目錄下執(zhí)行
編譯:make
安裝:make install

下載 redis/bin/redis.conf 進行下列配置后上傳覆蓋原文件:
1. 注釋掉 bind 127.0.0.1
2. 設置 protected-mode 為 no
3. 建議設置密碼 requirepass xxx

在 redis/bin 下執(zhí)行命令使用配置文件方式后臺啟動 redis:
./redis-server redis.conf &

查看 redis 啟動狀態(tài):
ps -ef|grep redis

其他:
關閉 redis:redis-cli shutdown

連接問題參考:
1. 終端執(zhí)行,防火墻放行:firewall-cmd --zone=public --add-port=6379/tcp --permanent
2. 終端執(zhí)行,防火墻重啟:firewall-cmd --reload
3. 云服務器端口開放問題:在實例-》安全組管理中開放 6379 端口

Spring Boot 中使用 Redis

1. 添加 pom

<!-- spring-boot-starter-data-redis 若需要指定版本號自行 maven 倉庫中找 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2. 添加配置

spring:
  redis:
    database: 0
    host: xxxxx      # Redis服務器地址,修改為你的地址
    port: 6379              # Redis服務器連接端口
    password: xxxxx          # Redis服務器連接密碼(默認為空)
    timeout: 3000           # Redis服務器鏈接超時配置

3. 導入 redis 工具類

PS:redis 工具類對常用操作進行了封裝,可自行研究食用。文章來源地址http://www.zghlxwxcb.cn/news/detail-413226.html

/**
 * Redis 工具類
 */
@Component
public class RedisUtil {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    // public RedisUtil(RedisTemplate<String, Object> redisTemplate) {
    //     this.redisTemplate = redisTemplate;
    // }

    /**
     * 指定緩存失效時間
     *
     * @param key  鍵
     * @param time 時間(秒)
     * @return
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根據(jù)key 獲取過期時間
     *
     * @param key 鍵 不能為null
     * @return 時間(秒) 返回0代表為永久有效
     */
    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 判斷key是否存在
     *
     * @param key 鍵
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 刪除緩存
     *
     * @param key 可以傳一個值 或多個
     */
    @SuppressWarnings("unchecked")
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
            }
        }
    }

    //============================String=============================

    /**
     * 普通緩存獲取
     *
     * @param key 鍵
     * @return 值
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 普通緩存放入
     *
     * @param key   鍵
     * @param value 值
     * @return true成功 false失敗
     */
    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 普通緩存放入并設置時間
     *
     * @param key   鍵
     * @param value 值
     * @param time  時間(秒) time要大于0 如果time小于等于0 將設置無限期
     * @return true成功 false 失敗
     */
    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 分布式鎖
     * @param key               鎖住的key
     * @param lockExpireMils    鎖住的時長。如果超時未解鎖,視為加鎖線程死亡,其他線程可奪取鎖
     * @return
     */
    public boolean setNx(String key, Long lockExpireMils) {
        // new RedisCallback<>() {
        //     @Override
        //     public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
        //         return null;
        //     }
        // };
        return (boolean) redisTemplate.execute((RedisCallback) connection -> {
            //獲取鎖
            /*
              setNX(k,v):如果該鍵不存在,則設置該鍵的值為指定的字符串;否則不做任何事情;
              使用 setNX() 命令可以實現(xiàn)分布式鎖等功能,因為該命令在設置鍵值對時是具有原子性的。
              在多線程或多進程環(huán)境中,如果多個線程或進程同時嘗試使用 setNX() 命令來設置同一個鍵,
              只有一個線程或進程能夠成功地設置,其他線程或進程會失敗,從而實現(xiàn)了互斥操作。
             */
            return connection.setNX(key.getBytes(), String.valueOf(System.currentTimeMillis() + lockExpireMils + 1).getBytes());
        });
    }

    /**
     * 遞增
     *
     * @param key   鍵
     * @param delta 要增加幾(大于0)
     * @return
     */
    public long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("遞增因子必須大于0");
        }
        // 將指定 key 的值增加 delta。如果 key 不存在,則會先創(chuàng)建一個初始值為 0 的 key,然后再執(zhí)行增加操作。
        return redisTemplate.opsForValue().increment(key, delta);
    }

    /**
     * 遞減
     *
     * @param key   鍵
     * @param delta 要減少幾(小于0)
     * @return
     */
    public long decr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("遞減因子必須大于0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }

    //================================Map=================================

    /**
     * HashGet
     *
     * @param key  鍵 不能為null
     * @param item 項 不能為null
     * @return 值
     */
    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }

    /**
     * 獲取hashKey對應的所有鍵值
     *
     * @param key 鍵
     * @return 對應的多個鍵值
     */
    public Map<Object, Object> hmget(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * HashSet
     *
     * @param key 鍵
     * @param map 對應多個鍵值
     * @return true 成功 false 失敗
     */
    public boolean hmset(String key, Map<String, Object> map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * HashSet 并設置時間
     *
     * @param key  鍵
     * @param map  對應多個鍵值
     * @param time 時間(秒)
     * @return true成功 false失敗
     */
    public boolean hmset(String key, Map<String, Object> map, long time) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一張hash表中放入數(shù)據(jù),如果不存在將創(chuàng)建
     *
     * @param key   鍵
     * @param item  項
     * @param value 值
     * @return true 成功 false失敗
     */
    public boolean hset(String key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一張hash表中放入數(shù)據(jù),如果不存在將創(chuàng)建
     *
     * @param key   鍵
     * @param item  項
     * @param value 值
     * @param time  時間(秒)  注意:如果已存在的hash表有時間,這里將會替換原有的時間
     * @return true 成功 false失敗
     */
    public boolean hset(String key, String item, Object value, long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 刪除hash表中的值
     *
     * @param key  鍵 不能為null
     * @param item 項 可以使多個 不能為null
     */
    public void hdel(String key, Object... item) {
        redisTemplate.opsForHash().delete(key, item);
    }

    /**
     * 判斷hash表中是否有該項的值
     *
     * @param key  鍵 不能為null
     * @param item 項 不能為null
     * @return true 存在 false不存在
     */
    public boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }

    /**
     * hash遞增 如果不存在,就會創(chuàng)建一個 并把新增后的值返回
     *
     * @param key  鍵
     * @param item 項
     * @param by   要增加幾(大于0)
     * @return
     */
    public double hincr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, by);
    }

    /**
     * hash遞減
     *
     * @param key  鍵
     * @param item 項
     * @param by   要減少記(小于0)
     * @return
     */
    public double hdecr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, -by);
    }

    //============================set=============================

    /**
     * 根據(jù)key獲取Set中的所有值
     *
     * @param key 鍵
     * @return
     */
    public Set<Object> sGet(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根據(jù)value從一個set中查詢,是否存在
     *
     * @param key   鍵
     * @param value 值
     * @return true 存在 false不存在
     */
    public boolean sHasKey(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 將數(shù)據(jù)放入set緩存
     *
     * @param key    鍵
     * @param values 值 可以是多個
     * @return 成功個數(shù)
     */
    public long sSet(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 將set數(shù)據(jù)放入緩存
     *
     * @param key    鍵
     * @param time   時間(秒)
     * @param values 值 可以是多個
     * @return 成功個數(shù)
     */
    public long sSetAndTime(String key, long time, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0) {
                expire(key, time);
            }
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 獲取set緩存的長度
     *
     * @param key 鍵
     * @return
     */
    public long sGetSetSize(String key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 移除值為value的
     *
     * @param key    鍵
     * @param values 值 可以是多個
     * @return 移除的個數(shù)
     */
    public long setRemove(String key, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    //===============================list=================================

    /**
     * 獲取list緩存的內容
     *
     * @param key   鍵
     * @param start 開始
     * @param end   結束  0 到 -1代表所有值
     * @return
     */
    public List<Object> lGet(String key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 獲取list緩存的長度
     *
     * @param key 鍵
     * @return
     */
    public long lGetListSize(String key) {
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 通過索引 獲取list中的值
     *
     * @param key   鍵
     * @param index 索引  index>=0時, 0 表頭,1 第二個元素,依次類推;index<0時,-1,表尾,-2倒數(shù)第二個元素,依次類推
     * @return
     */
    public Object lGetIndex(String key, long index) {
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 將list放入緩存
     *
     * @param key   鍵
     * @param value 值
     * @return
     */
    public boolean lSet(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 將list放入緩存
     *
     * @param key   鍵
     * @param value 值
     * @param time  時間(秒)
     * @return
     */
    public boolean lSet(String key, Object value, long time) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 將list放入緩存
     *
     * @param key   鍵
     * @param value 值
     * @return
     */
    public boolean lSet(String key, List<Object> value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 將list放入緩存
     *
     * @param key   鍵
     * @param value 值
     * @param time  時間(秒)
     * @return
     */
    public boolean lSet(String key, List<Object> value, long time) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根據(jù)索引修改list中的某條數(shù)據(jù)
     *
     * @param key   鍵
     * @param index 索引
     * @param value 值
     * @return
     */
    public boolean lUpdateIndex(String key, long index, Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 移除N個值為value
     *
     * @param key   鍵
     * @param count 移除多少個
     * @param value 值
     * @return 移除的個數(shù)
     */
    public long lRemove(String key, long count, Object value) {
        try {
            Long remove = redisTemplate.opsForList().remove(key, count, value);
            return remove;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 模糊查詢獲取key值
     *
     * @param pattern
     * @return
     */
    public Set keys(String pattern) {
        return redisTemplate.keys(pattern);
    }

    /**
     * 使用Redis的消息隊列
     *
     * @param channel
     * @param message 消息內容
     */
    public void convertAndSend(String channel, Object message) {
        redisTemplate.convertAndSend(channel, message);
    }


    //=========BoundListOperations 用法 start============

    /**
     * 將數(shù)據(jù)添加到Redis的list中(從右邊添加)
     *
     * @param listKey
     * @param timeout 有效時間
     * @param unit    時間類型
     * @param values  待添加的數(shù)據(jù)
     */
    public void addToListRight(String listKey, long timeout, TimeUnit unit, Object... values) {
        //綁定操作
        BoundListOperations<String, Object> boundValueOperations = redisTemplate.boundListOps(listKey);
        //插入數(shù)據(jù)
        boundValueOperations.rightPushAll(values);
        //設置過期時間
        boundValueOperations.expire(timeout, unit);
    }

    /**
     * 根據(jù)起始結束序號遍歷Redis中的list
     *
     * @param listKey
     * @param start   起始序號
     * @param end     結束序號
     * @return
     */
    public List<Object> rangeList(String listKey, long start, long end) {
        //綁定操作
        BoundListOperations<String, Object> boundValueOperations = redisTemplate.boundListOps(listKey);
        //查詢數(shù)據(jù)
        return boundValueOperations.range(start, end);
    }

    /**
     * 彈出右邊的值 --- 并且移除這個值
     *
     * @param listKey
     */
    public Object rightPop(String listKey) {
        //綁定操作
        BoundListOperations<String, Object> boundValueOperations = redisTemplate.boundListOps(listKey);
        return boundValueOperations.rightPop();
    }

    //=========BoundListOperations 用法 End============

}

4. 測試

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTest {

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Test
    public void test_redis_util() {
        boolean flag = redisUtil.set("key", "value");
        String v = (String) redisUtil.get("key");
        System.out.println("flag = " + flag + " v = " + v);
    }

    @Test
    public void test_redisTemplate() {
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        ops.set("k1", "v1");
        System.out.println(ops.get("k1"));
    }
}    

到了這里,關于Spring Boot 中使用 Redis的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!

本文來自互聯(lián)網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。如若轉載,請注明出處: 如若內容造成侵權/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經查實,立即刪除!

領支付寶紅包贊助服務器費用

相關文章

  • Spring Boot中使用Redis

    Spring Boot中使用Redis

    目錄 1.依賴 2.依賴關系 3.配置 4.RedisTemplate 5.基礎操作 6.事務 maven依賴如下,需要說明的是,spring-boot-starter-data-redis里默認是使用lettuce作為redis客戶端的驅動,但是lettuce其實用的比較少,我們常用的還是jedis作為客戶端的驅動,所以這里排除掉lettuce,引入jedis: spring data redi

    2023年04月11日
    瀏覽(27)
  • Spring Boot 中使用 Redis

    redis 安裝、配置,啟動:(此處以云服務器上進行說明) 1. 添加 pom 2. 添加配置 3. 導入 redis 工具類 PS:redis 工具類對常用操作進行了封裝,可自行研究食用。 4. 測試

    2023年04月14日
    瀏覽(31)
  • spring boot中redis的使用

    首先,需要在 pom.xml 文件中添加Redis依賴: 這個依賴包含了Spring?Data?Redis,以及Jedis和Lettuce這兩種Redis客戶端的實現(xiàn)。 在SpringBoot項目中,可以通過在 application.properties 或 application.yml 文件中配置Redis連接信息。以下是一個示例: 其中, host 和 port 分別是Redis服務器的地址和端

    2024年02月09日
    瀏覽(19)
  • Spring Boot - 結合 Redis 使用 Lua腳本

    在Spring Boot中整合Redis并使用Lua腳本: 添加Spring Boot和Redis的依賴: 首先,在Spring Boot項目的 pom.xml 文件中添加Spring Boot和Spring Data Redis的依賴: 配置Redis連接: 在 application.properties 或 application.yml 中配置Redis的連接信息,以及 redis 配置: RedisConfig.java

    2024年02月08日
    瀏覽(19)
  • 使用Spring Boot實現(xiàn)Redis鍵過期回調功能

    使用Spring Boot實現(xiàn)Redis鍵過期回調功能

    當使用Redis作為緩存或數(shù)據(jù)存儲的時候,有時候需要在鍵過期時執(zhí)行一些特定的操作,比如清除相關數(shù)據(jù)或發(fā)送通知。在Spring Boot中,可以通過實現(xiàn) RedisMessageListener 接口來實現(xiàn)Redis鍵過期回調功能。下面是一個實現(xiàn)Redis鍵過期回調功能的Spring Boot應用的示例: 步驟一:引入依賴

    2024年02月16日
    瀏覽(22)
  • 如何在Spring Boot中使用Redis連接池?

    ??在Spring Boot中使用Redis連接池,你通常不需要做太多額外配置,因為Spring Boot Data Redis默認使用了一個連接池,即LettuceConnectionFactory或JedisConnectionFactory,它們內部已經實現(xiàn)了連接池功能。 ??下面是一些步驟和配置,以確保你在Spring Boot應用中正確使用了Redis連接池: ??

    2024年03月11日
    瀏覽(27)
  • 輕松打卡:使用Spring Boot和Redis Bitmap構建高效簽到系統(tǒng)【redis實戰(zhàn) 四】

    輕松打卡:使用Spring Boot和Redis Bitmap構建高效簽到系統(tǒng)【redis實戰(zhàn) 四】

    歡迎來到我的博客,代碼的世界里,每一行都是一個故事 Redis List:打造高效消息隊列的秘密武器【redis實戰(zhàn) 一】 Redis Streams在Spring Boot中的應用:構建可靠的消息隊列解決方案【redis實戰(zhàn) 二】 Spring Boot和Redis Geo實現(xiàn)附近的人【redis實戰(zhàn) 三】 在數(shù)字化時代,簽到系統(tǒng)已成為許多

    2024年01月23日
    瀏覽(17)
  • Spring Boot 整合 Redis,使用 RedisTemplate 客戶端

    Spring Boot 整合 Redis,使用 RedisTemplate 客戶端

    1.1.1 添加依賴 redis 的依賴: 1.1.2 yml 配置文件 1.1.3 Config 配置文件 1.1.4 使用示例 注入 RedisTemplate,即可操作 Redis,簡單示例如下: 1.2.1 RedisTemplate 簡介 RedisTemplate 是 Spring Data Redis 項目的一部分,旨在簡化在Java應用程序中使用 Redis 的過程。它提供了一組簡單的方法,可以在

    2024年02月09日
    瀏覽(28)
  • 使用Spring Boot操作Redis、ES、MongoDB舉例

    在Spring Boot應用程序中操作Redis通常涉及到使用Spring Data Redis,這是一個提供簡便方法來操作Redis的庫。以下是一個基本示例,演示如何在Spring Boot應用程序中集成和使用Redis: 步驟 1: 添加依賴項 首先,在你的 pom.xml 文件中添加Spring Data Redis的依賴項。 步驟 2: 配置Redis 在你的

    2024年01月25日
    瀏覽(21)
  • 在Spring Boot中使用Redis 5的Stream

    Redis是一個開源的高性能鍵值對存儲系統(tǒng),而Redis 5引入了新的數(shù)據(jù)結構——Stream(流)。Stream可以用于高效地保存和處理事件流數(shù)據(jù)。在本文中,我們將學習如何在Spring Boot應用程序中使用Redis 5的Stream功能。 步驟1:配置Redis連接 首先,確保您的Spring Boot應用程序已經添加了

    2024年02月09日
    瀏覽(22)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領取紅包,優(yōu)惠每天領

二維碼1

領取紅包

二維碼2

領紅包