Spring Boot + spring-data-redis

來源:互聯網
上載者:User

標籤:儲存   oca   介面調用   tar   static   web   boot   增加   ica   

Redis

Redis是緩衝, 訊息佇列, 多種類型的key-value儲存服務.

Spring Boot

Spring Boot為Lettcue和Jedis用戶端提供自動注入配置, 並且通過spring-data-redis提供抽象介面

配置串連Redis服務和介面調用1. 加入依賴

pom.xml 的依賴集合中加入 org.springframework.boot:spring-boot-starter-data-reids 依賴, 如下配置

    <dependencies>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-web</artifactId>        </dependency>        <!-- 裡面依賴了spring-data-redis -->        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-data-redis</artifactId>        </dependency>    </dependencies>

預設使用 Lettuce 作為用戶端

2. 修改設定檔

在spring boot設定檔中增加redis相關的配置, 以 application.yaml 為例 (其他格式設定檔,自行轉換)

spring:  redis:    # 其他配置資訊有預設    host: localhost    port: 6379    timeout: 500    pool:      min-idle: 1      max-idle: 8      max-active: 8
3. Bean注入使用

如上配置完成之後, Spring Boot 自動注入管理 RedisTemplate. 可以通過該對象操作Redis.

按照我以往的簡潔的做法, 我 在RedisTemple 上在封裝成簡潔明了的操作. 如下管理

RedisManager.java

package info.chiwm.boot.manager;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.StringRedisTemplate;import org.springframework.stereotype.Component;import javax.annotation.PostConstruct;/** * @author [email protected] * @ClassName: RedisManager * @Description: * @date 2018/1/10 下午3:40 */@Componentpublic class RedisManager {    @Autowired    private StringRedisTemplate redisTemplate;    private static RedisManager redisManager;    @PostConstruct    public void init() {        redisManager = this;    }    /**     * Redis Set String Ops     *     * @param key     * @param value     */    public static void set(String key, String value) {        redisManager.redisTemplate.opsForValue().set(key, value);    }    /**     * Redis Get String Ops     * @param key     * @return     */    public static String get(String key) {        return redisManager.redisTemplate.opsForValue().get(key);    }}

直接調用靜態方法的方式, 方便的調用Redis對應的set key命令. 如果還需其他儲存類型和操作. 可以在 RedisManager 上增加靜態方法.

Spring Boot + spring-data-redis

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.