十、spring boot 2.x 集成 redis

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LDY1016/article/details/83503277

 Redis的安装教程:https://blog.csdn.net/LDY1016/article/details/76083162

1、在pom.xml中添加redis和连接池的maven依赖

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

2、在application.properties中添加redis的配置信息

#redis
#单节点
spring.redis.host = 127.0.0.1
spring.redis.port = 6379
#多节点
#spring.redis.cluster.nodes = 127.0.0.1:7001,127.0.0.1:7002,127.0.0.1:7003
#密码,没有密码可以注释掉
#spring.redis.password = 123456
# 连接超时时间 单位 ms(毫秒)
spring.redis.timeout = 6000
# 连接池中的最大空闲连接,默认值也是8
spring.redis.lettuce.pool.max-idle = 8
# 连接池中的最小空闲连接,默认值也是0
spring.redis.lettuce.pool.min-idle = 0
# 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
spring.redis.lettuce.pool.max-active = 8 
# 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出
spring.redis.lettuce.pool.max-wait = -1

说明:spring boot 2.x中redis连接池的配置有所变更,在1.x中连接池的配置如下:

# 连接池中的最大空闲连接,默认值也是8
spring.redis.pool.max-idle = 8
# 连接池中的最小空闲连接,默认值也是0
spring.redis.pool.min-idle = 0
# 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
spring.redis.pool.max-active = 8 
# 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出
spring.redis.pool.max-wait = -1

相较于1.x版本,2.x版本从spring.redis.pool变更为spring.redis.lettuce.pool

3、编写java代码:RedisService.java

package com.ldy.bootv2.demo.service;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
 
@Service
public class RedisService {
 
	private static Logger logger = LoggerFactory.getLogger(RedisService.class);
	
	@Autowired
	private StringRedisTemplate redisTemplate;
 
	/**
	 * 写入redis缓存(不设置expire存活时间)
	 * @param key
	 * @param value
	 * @return
	 */
	public boolean set(final String key, String value) {
		boolean result = false;
		try {
			ValueOperations<String, String> operations = redisTemplate.opsForValue();
			operations.set(key, value);
			result = true;
		} catch (Exception e) {
			logger.error("写入redis缓存失败!错误信息为:" + e.getMessage());
		}
		return result;
	}
 
	/**
	 * 写入redis缓存(设置expire存活时间)
	 * @param key
	 * @param value
	 * @param expire
	 * @return
	 */
	public boolean set(final String key, String value, Long expire) {
		boolean result = false;
		try {
			ValueOperations<String, String> operations = redisTemplate.opsForValue();
			operations.set(key, value);
			redisTemplate.expire(key, expire, TimeUnit.SECONDS);
			result = true;
		} catch (Exception e) {
			logger.error("写入redis缓存(设置expire存活时间)失败!错误信息为:" + e.getMessage());
		}
		return result;
	}
 
	/**
	 * 读取redis缓存
	 * 
	 * @param key
	 * @return
	 */
	public Object get(final String key) {
		Object result = null;
		try {
			ValueOperations<String, String> operations = redisTemplate.opsForValue();
			result = operations.get(key);
		} catch (Exception e) {
			logger.error("读取redis缓存失败!错误信息为:" + e.getMessage());
		}
		return result;
	}
 
	/**
	 * 判断redis缓存中是否有对应的key
	 * @param key
	 * @return
	 */
	public boolean exists(final String key) {
		boolean result = false;
		try {
			result = redisTemplate.hasKey(key);
		} catch (Exception e) {
			logger.error("判断redis缓存中是否有对应的key失败!错误信息为:" + e.getMessage());
		}
		return result;
	}
 
	/**
	 * redis根据key删除对应的value
	 * @param key
	 * @return
	 */
	public boolean remove(final String key) {
		boolean result = false;
		try {
			if (exists(key)) {
				redisTemplate.delete(key);
			}
			result = true;
		} catch (Exception e) {
			logger.error("redis根据key删除对应的value失败!错误信息为:" + e.getMessage());
		}
		return result;
	}
 
	/**
	 * redis根据keys批量删除对应的value
	 * 
	 * @param keys
	 * @return
	 */
	public void remove(final String... keys) {
		for (String key : keys) {
			remove(key);
		}
	}
 
}

4、编写接口测试redis相关操作:RedisController.java

package com.ldy.bootv2.demo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ldy.bootv2.demo.service.RedisService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@Api(tags = "REDIS-TEST-API")
@RestController
@RequestMapping(value = "/redis")
public class RedisController {
	
	private static Logger log = LoggerFactory.getLogger(RedisController.class);
	
	@Autowired
	private RedisService redisService;
	
	
	@PostMapping("/sendToRedis")
	@ApiOperation("将数据存放到redis中")
	@ApiImplicitParams({
	    @ApiImplicitParam(name = "key", value = "键", required = true, dataType = "String"),
            @ApiImplicitParam(name = "value", value = "值", required = false, dataType = "String") })
	public ModelMap sendToRedis(@RequestParam String key, @RequestParam String value) {
		log.debug("您调用了sendToRedis接口");
		ModelMap model = new ModelMap();
		redisService.set(key, value, 1*60L);//1分钟失效
		model.put("status", "success");
		model.put("msg", "成功");

		return model;
	}
	
	@GetMapping("/getFromRedis")
	@ApiOperation("从redis获取信息接口")
	@ApiImplicitParam(name = "key", value = "键", required = true, dataType = "String")
	public ModelMap getFromRedis(@RequestParam String key) {
		log.debug("您调用了getFromRedis接口");
		ModelMap model = new ModelMap();
		Object ch = redisService.get(key);
		model.put("status", "success");
		model.put("msg", "获取到的值为:" + String.valueOf(ch));

		return model;
	}

}

5、运行项目,打开swagger页面,测试接口正常,swagger的集成请查看:https://blog.csdn.net/LDY1016/article/details/83415640

源码下载地址:https://pan.baidu.com/s/1Z771VDiuabDBJJV445xLeA#list/path=%2Fspring%20boot%202.x%20%E4%BB%A3%E7%A0%81

猜你喜欢

转载自blog.csdn.net/LDY1016/article/details/83503277