SpringBoot2.0整合Redis


Spring Boot2.0在2018年3月份正式發布,相比1.0還是有比較多的改動,例如SpringBoot 自2.0起支持jdk1.8及以上的版本、第三方類庫升級、響應式 Spring 編程支持等;整合Redis也有所變化,下面詳細介紹下基於Spring Boot2.1.2.RELEASE版本整合redis的過程。

一、pom.xml中引入jar

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

二、在application.yml中配置redis連接信息

spring:
  redis:
    host: 192.168.0.1
    password: 1111
    port: 6379
    database: 0
    timeout: 60s  # 數據庫連接超時時間,2.0 中該參數的類型為Duration,這里在配置的時候需要指明單位
    # 連接池配置,2.0中直接使用jedis或者lettuce配置連接池
    jedis:
      pool:
        # 最大空閑連接數
        max-idle: 500
        # 最小空閑連接數
        min-idle: 50
        # 等待可用連接的最大時間,負數為不限制
        max-wait:  -1s
        # 最大活躍連接數,負數為不限制
        max-active: -1

三、編寫RedisController,測試set、get命令

操作redis可以使用下面兩個template

  1. StringRedisTemplate,存儲字符串類型
  2. RedisTemplate, 存儲對象類型

代碼如下:

package com.example.helloSpringBoot.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RedisController {

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/set")
    public String HelloSpring (String key,String value){
        redisTemplate.opsForValue().set(key,value);
        return String.format("redis set成功!key=%2,value=%s",key,value);
    }

    @RequestMapping("/get")
    public String HelloSpring (String key){
        String value = (String) redisTemplate.opsForValue().get(key);
        return "redis get結果 value=" + value;
    }
}
  1. postman發送請求訪問http://localhost:8080/set

截圖如下:

訪問set截圖

 

  1. postman發送請求訪問http://localhost:8080/get

截圖如下:

訪問get截圖

 

限時領取免費Java相關資料,涵蓋了Java、Redis、MongoDB、MySQL、Zookeeper、Spring Cloud、Dubbo/Kafka、Hadoop、Hbase、Flink等高並發分布式、大數據、機器學習等技術。

資料傳送門:https://mp.weixin.qq.com/s/u2b_NVNuMuAPE0w4lc45fw

 

關注下方公眾號即可免費領取:

Java碎碎念公眾號

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM