Spring Boot整合redis

Spring Boot本身对redis有较好的集成,使用起来也非常地方便,下面简单介绍下使用步骤。

1、pom.xml依赖添加


    org.springframework.boot
    spring-boot-starter-web


    org.springframework.boot
    spring-boot-starter-data-redis
    2.0.6.RELEASE

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 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:

你可能感兴趣的:(Spring,Boot)