前言
一直没机会做spring生态圈的框架,公司选择的是一些小众的微服务,鉴于此考虑,丰富自己的技术栈,花了两天时间从网上各网站上学习了springboot一些基础知识。 本章只介绍springboot微服务集成redis,用于存放或访问项目中用到的缓存数据库。
环境准备
- IntelliJ IDEA
- 前一章中搭建的微服务框架
开始集成
- pom.xml中增加依赖包
<dependency> | |
<groupId>org.springframework.boot</groupId> | |
<artifactId>spring-boot-starter-data-redis</artifactId> | |
</dependency> |
- 在application.yml中配置redis服务连接信息:
spring: | |
#日志记录模式 | |
profiles: | |
active: dev | |
banner: | |
charset: "UTF-8" | |
location: classpath:/banner.txt | |
datasource: | |
url: jdbc:mysql://localhost:3306/test | |
username: root | |
password: xxx | |
driver-class-name: com.mysql.cj.jdbc.Driver | |
redis: | |
#url: redis://user:password@example.com:6379 | |
#redis机器ip | |
host: 127.0.0.1 | |
#redis端口 | |
port: 6379 | |
#redis密码 | |
password: | |
#redis超时时间(毫秒),如果不设置,取默认值2000 | |
timeout: 10000 | |
jedis: | |
pool: | |
#最大空闲数 | |
maxIdle: 300 | |
#连接池的最大数据库连接数。设为0表示无限制,如果是jedis 2.4以后用redis.maxTotal | |
maxActive: 600 | |
#控制一个pool可分配多少个jedis实例,用来替换上面的redis.maxActive,如果是jedis 2.4以后用该属性 | |
#maxTotal: 1000 | |
#最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。 | |
maxWait: 1000 | |
#连接的最小空闲时间 默认1800000毫秒(30分钟) | |
#minEvictableIdleTimeMillis: 300000 | |
#每次释放连接的最大数目,默认3 | |
#numTestsPerEvictionRun: 1024 | |
#逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1 | |
timeBetweenEvictionRuns: 30000 | |
#是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个 | |
#testOnBorrow: true | |
#在空闲时检查有效性, 默认false | |
#testWhileIdle: true |
- 在demo包下编写redis配置类,用于接收并解析yml中所配置的redis服务信息,并可以构建redis模板,redis连接工厂:
package com.example.demo; | |
import org.springframework.boot.autoconfigure.AutoConfigureAfter; | |
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; | |
import org.springframework.context.annotation.Bean; | |
import org.springframework.context.annotation.Configuration; | |
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; | |
import org.springframework.data.redis.core.RedisTemplate; | |
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; | |
import org.springframework.data.redis.serializer.StringRedisSerializer; | |
import java.io.Serializable; | |
/** | |
* 类功能描述:<br> | |
* <ul> | |
* <li>类功能描述1<br> | |
* <li>类功能描述2<br> | |
* <li>类功能描述3<br> | |
* </ul> | |
* 修改记录:<br> | |
* <ul> | |
* <li>修改记录描述1<br> | |
* <li>修改记录描述2<br> | |
* <li>修改记录描述3<br> | |
* </ul> | |
* | |
* @author xuefl | |
* @version 5.0 since 2020-01-02 | |
*/ | |
public class RedisConfig { | |
public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) { | |
RedisTemplate<String, Serializable> template = new RedisTemplate<>(); | |
template.setKeySerializer(new StringRedisSerializer()); | |
template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); | |
template.setConnectionFactory(redisConnectionFactory); | |
return template; | |
} | |
} |
- 为了方便后续对Redis数据库中数据的操作,在util包下新增redis操作工具类:
package com.example.demo.util; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.data.redis.core.*; | |
import org.springframework.stereotype.Service; | |
import java.io.Serializable; | |
import java.util.List; | |
import java.util.Set; | |
import java.util.concurrent.TimeUnit; | |
/** | |
* 类功能描述:<br> | |
* <ul> | |
* <li>类功能描述1<br> | |
* <li>类功能描述2<br> | |
* <li>类功能描述3<br> | |
* </ul> | |
* 修改记录:<br> | |
* <ul> | |
* <li>修改记录描述1<br> | |
* <li>修改记录描述2<br> | |
* <li>修改记录描述3<br> | |
* </ul> | |
* | |
* @author xuefl | |
* @version 5.0 since 2020-01-02 | |
*/ | |
public class RedisUtil { | |
private RedisTemplate redisTemplate; | |
/** | |
* 写入缓存 | |
* @param key | |
* @param value | |
* @return | |
*/ | |
public boolean set(final String key, Object value) { | |
boolean result = false; | |
try { | |
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); | |
operations.set(key, value); | |
result = true; | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
return result; | |
} | |
/** | |
* 写入缓存设置时效时间 | |
* @param key | |
* @param value | |
* @return | |
*/ | |
public boolean set(final String key, Object value, Long expireTime , TimeUnit timeUnit) { | |
boolean result = false; | |
try { | |
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); | |
operations.set(key, value); | |
redisTemplate.expire(key, expireTime, timeUnit); | |
result = true; | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
return result; | |
} | |
/** | |
* 批量删除对应的value | |
* @param keys | |
*/ | |
public void remove(final String... keys) { | |
for (String key : keys) { | |
remove(key); | |
} | |
} | |
/** | |
* 批量删除key | |
* @param pattern | |
*/ | |
public void removePattern(final String pattern) { | |
Set<Serializable> keys = redisTemplate.keys(pattern); | |
if (keys.size() > 0){ | |
redisTemplate.delete(keys); | |
} | |
} | |
/** | |
* 删除对应的value | |
* @param key | |
*/ | |
public void remove(final String key) { | |
if (exists(key)) { | |
redisTemplate.delete(key); | |
} | |
} | |
/** | |
* 判断缓存中是否有对应的value | |
* @param key | |
* @return | |
*/ | |
public boolean exists(final String key) { | |
return redisTemplate.hasKey(key); | |
} | |
/** | |
* 读取缓存 | |
* @param key | |
* @return | |
*/ | |
public Object get(final String key) { | |
Object result = null; | |
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); | |
result = operations.get(key); | |
return result; | |
} | |
/** | |
* 哈希 添加 | |
* @param key | |
* @param hashKey | |
* @param value | |
*/ | |
public void hmSet(String key, Object hashKey, Object value){ | |
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash(); | |
hash.put(key,hashKey,value); | |
} | |
/** | |
* 哈希获取数据 | |
* @param key | |
* @param hashKey | |
* @return | |
*/ | |
public Object hmGet(String key, Object hashKey){ | |
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash(); | |
return hash.get(key,hashKey); | |
} | |
/** | |
* 列表添加 | |
* @param k | |
* @param v | |
*/ | |
public void lPush(String k,Object v){ | |
ListOperations<String, Object> list = redisTemplate.opsForList(); | |
list.rightPush(k,v); | |
} | |
/** | |
* 列表获取 | |
* @param k | |
* @param l | |
* @param l1 | |
* @return | |
*/ | |
public List<Object> lRange(String k, long l, long l1){ | |
ListOperations<String, Object> list = redisTemplate.opsForList(); | |
return list.range(k,l,l1); | |
} | |
/** | |
* 集合添加 | |
* @param key | |
* @param value | |
*/ | |
public void add(String key,Object value){ | |
SetOperations<String, Object> set = redisTemplate.opsForSet(); | |
set.add(key,value); | |
} | |
/** | |
* 集合获取 | |
* @param key | |
* @return | |
*/ | |
public Set<Object> setMembers(String key){ | |
SetOperations<String, Object> set = redisTemplate.opsForSet(); | |
return set.members(key); | |
} | |
/** | |
* 有序集合添加 | |
* @param key | |
* @param value | |
* @param scoure | |
*/ | |
public void zAdd(String key,Object value,double scoure){ | |
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet(); | |
zset.add(key,value,scoure); | |
} | |
/** | |
* 有序集合获取 | |
* @param key | |
* @param scoure | |
* @param scoure1 | |
* @return | |
*/ | |
public Set<Object> rangeByScore(String key,double scoure,double scoure1){ | |
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet(); | |
return zset.rangeByScore(key, scoure, scoure1); | |
} | |
} |
- 定义redis controller类,在controller包下编写RedisController类:
package com.example.demo.controller; | |
import com.example.demo.util.RedisUtil; | |
import io.swagger.annotations.Api; | |
import io.swagger.annotations.ApiOperation; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.http.MediaType; | |
import org.springframework.web.bind.annotation.GetMapping; | |
import org.springframework.web.bind.annotation.RequestMapping; | |
import org.springframework.web.bind.annotation.RequestMethod; | |
import org.springframework.web.bind.annotation.RestController; | |
/** | |
* 类功能描述:<br> | |
* <ul> | |
* <li>类功能描述1<br> | |
* <li>类功能描述2<br> | |
* <li>类功能描述3<br> | |
* </ul> | |
* 修改记录:<br> | |
* <ul> | |
* <li>修改记录描述1<br> | |
* <li>修改记录描述2<br> | |
* <li>修改记录描述3<br> | |
* </ul> | |
* | |
* @author xuefl | |
* @version 5.0 since 2020-01-02 | |
*/ | |
public class RedisController { | |
private RedisUtil redisUtil; | |
//添加 | |
public boolean saveRedis(){ | |
return redisUtil.set("a","test"); | |
} | |
//获取 | |
public Object getRedis(){ | |
return redisUtil.get("a"); | |
} | |
} |
此类注入redisUtil工具类,引用其对数据的CURD方法,进行业务操作,然后定义相关的uri,用于http访问,此处只定义了两个:一个新增key-value、一个查询key。
- 启动DemoApplication类,访问swagger页面测试结果: