Spring Boot整合redis

Spring Boot本身對redis有較好的集成,使用起來也非常地方便,下面簡單介紹下使用步驟。

1、pom.xml依賴添加

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>2.0.6.RELEASE</version>
</dependency>

2、redis數據源配置

在application.properties中添加:

# Redis數據庫索引(默認爲0)

spring.redis.database=0

# Redis服務器地址

spring.redis.host=XXX

# Redis服務器連接端口

spring.redis.port=6379

# Redis服務器連接密碼(默認爲空)

spring.redis.password=XXX

# 連接池最大連接數(使用負值表示沒有限制)

spring.redis.pool.max-active=1000

# 連接池最大阻塞等待時間(使用負值表示沒有限制)

spring.redis.pool.max-wait=-1

# 連接池中的最大空閒連接

spring.redis.pool.max-idle=10

# 連接池中的最小空閒連接

spring.redis.pool.min-idle=2

# 連接超時時間(毫秒)

spring.redis.timeout=50

3、Controller層代碼

package com.henry.web.springbootweb.controller;

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

@RestController
public class RedisController {
	
	@Autowired
	// 調用模板在啓動Spring Boot後自動注入
	private RedisTemplate<String,String> stringRedisTemplate;

	@RequestMapping("/setandget/{key}/{value}")
	public String setAndGet(@PathVariable("key") String key,
			@PathVariable("value") String value) {
		try {
			// 設置值
			this.stringRedisTemplate.opsForValue().set(key, value);
			// 獲取值
			System.out.println(this.stringRedisTemplate.opsForValue().get(key));
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
		return "success";
	}
}

4、啓動SpringBoot運行結果

瀏覽器:

redis:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章