如何自定义一个springboot starter项目
- 一、需求
- 二、选择的连接方式
- 三、实现步骤
- 3.1 新建Maven项目
- 3.2 引入依赖
- 3.3 定义redis配置文件
- 3.4 自定义redis自动装配类
- 3.5 创建spring.factories文件
- 3.6 创建配置项说明
- 3.7 redis工具类
- 3.7.1 新建RedisClient类
- 3.7.1 添加类路径到spring.factories文件中
- 四、使用方法
一、需求
在搭建微服务项目时,有多个项目需要整合redis,就需要在每个项目中都引入redis依赖和进行redis的配置。就需要我们自定义一个redis的starter,项目中引入这个starter之后,只需要引入starter的依赖,在配置文件中引入redis的连接配置即可使用。
二、选择的连接方式
不使用默认的lettuce方式,这里我们使用jedis
三、实现步骤
3.1 新建Maven项目
3.2 引入依赖
<properties>
<starter.version>2.3.9.RELEASE</starter.version>
<configuration.version>2.3.9.RELEASE</configuration.version>
<jedis.version>3.1.0</jedis.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>${starter.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>${configuration.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>${starter.version}</version>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${jedis.version}</version>
</dependency>
</dependencies>
3.3 定义redis配置文件
@ConfigurationProperties(prefix = "spring.redis")
public class RedissonProperties {
private String host;
private Integer port;
private String password;
private Integer dataBase = 0;
private Integer maxActive;
private Integer maxIdle;
private Integer minIdle = 0;
private Long maxWait = 10000L;
private Integer timeout = 5000;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getDataBase() {
return dataBase;
}
public void setDataBase(Integer dataBase) {
this.dataBase = dataBase;
}
public Integer getMaxActive() {
return maxActive;
}
public void setMaxActive(Integer maxActive) {
this.maxActive = maxActive;
}
public Integer getMaxIdle() {
return maxIdle;
}
public void setMaxIdle(Integer maxIdle) {
this.maxIdle = maxIdle;
}
public Integer getMinIdle() {
return minIdle;
}
public void setMinIdle(Integer minIdle) {
this.minIdle = minIdle;
}
public Long getMaxWait() {
return maxWait;
}
public void setMaxWait(Long maxWait) {
this.maxWait = maxWait;
}
public Integer getTimeout() {
return timeout;
}
public void setTimeout(Integer timeout) {
this.timeout = timeout;
}
}
3.4 自定义redis自动装配类
@Configuration
@EnableConfigurationProperties(RedissonProperties.class)
public class RedissonAutoConfiguration {
@Resource
private RedissonProperties redissonProperties;
@Bean(name = "redisTemplate")
public RedisTemplate redisTemplate() {
RedisTemplate backUpRedisTemplate = getRedisConnectionFactory();
return backUpRedisTemplate;
}
private RedisTemplate getRedisConnectionFactory() {
JedisConnectionFactory jedisFactory = new JedisConnectionFactory();
jedisFactory.setHostName(redissonProperties.getHost());
jedisFactory.setPort(redissonProperties.getPort());
jedisFactory.setPassword(redissonProperties.getPassword());
jedisFactory.setDatabase(redissonProperties.getDataBase());
jedisFactory.setTimeout(redissonProperties.getTimeout());
JedisPoolConfig poolConfig = new JedisPoolConfig(); // 进行连接池配置
poolConfig.setMaxTotal(redissonProperties.getMaxActive());
poolConfig.setMaxIdle(redissonProperties.getMaxIdle());
poolConfig.setMinIdle(redissonProperties.getMinIdle());
poolConfig.setMaxWaitMillis(redissonProperties.getMaxWait());
jedisFactory.setPoolConfig(poolConfig);
jedisFactory.afterPropertiesSet(); // 初始化连接池配置
RedisTemplate<String, Object> redisTemplate = new RedisTemplate();
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setConnectionFactory(jedisFactory);
return redisTemplate;
}
}
3.5 创建spring.factories文件
在resource目录下新建MATA-INF/spring.factories文件,在其他项目引入该starter时回去加载该文件,从而找到RedissonAutoConfiguration类进行自动装配
在spring.factories文件中配置:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.xiaoniu.redisson.config.RedissonAutoConfiguration
3.6 创建配置项说明
在resource目录下新建MATA-INF/additional-spring-configuration-metadata.json文件
在additional-spring-configuration-metadata.json文件中配置:
{
"properties": [
{
"name": "spring.redis.port",
"type": "java.lang.Integer",
"sourceType": "com.xiaoniu.redisson.properties.RedissonProperties",
"defaultValue": 6379,
"description": "端口"
},
{
"name": "spring.redis.host",
"type": "java.lang.String",
"sourceType": "com.xiaoniu.redisson.properties.RedissonProperties",
"defaultValue": "localhost",
"description": "ip"
},
{
"name": "spring.redis.password",
"type": "java.lang.String",
"sourceType": "com.xiaoniu.redisson.properties.RedissonProperties",
"defaultValue": "",
"description": "密码"
},
{
"name": "spring.redis.dataBase",
"type": "java.lang.Integer",
"sourceType": "com.xiaoniu.redisson.properties.RedissonProperties",
"defaultValue": 0,
"description": "数据库编号"
},
{
"name": "spring.redis.maxActive",
"type": "java.lang.Integer",
"sourceType": "com.xiaoniu.redisson.properties.RedissonProperties",
"defaultValue": "",
"description": "最大连接数"
},
{
"name": "spring.redis.maxIdle",
"type": "java.lang.Integer",
"sourceType": "com.xiaoniu.redisson.properties.RedissonProperties",
"defaultValue": "",
"description": "连接池最大空闲连接数"
},
{
"name": "spring.redis.maxWait",
"type": "java.lang.Long",
"sourceType": "com.xiaoniu.redisson.properties.RedissonProperties",
"defaultValue": 10000,
"description": "连接池最大阻塞等待时间(使用负值表示没有限制)"
},
{
"name": "spring.redis.minIdle",
"type": "java.lang.Integer",
"sourceType": "com.xiaoniu.redisson.properties.RedissonProperties",
"defaultValue": 0,
"description": "连接池最小空闲连接"
},
{
"name": "spring.redis.timeout",
"type": "java.lang.Integer",
"sourceType": "com.xiaoniu.redisson.properties.RedissonProperties",
"defaultValue": 5000,
"description": "超时时间"
}
]
}
这个文件中的每一项与RedissonProperties类中的属性一一对应。
字段说明: name:属性名
type:类型
sourceType:配置类路径
defaultValue:默认值
description:属性说明
到这一步其实该starter已经可以使用了。使用方法如下: 四、使用方法
3.7 redis工具类
3.7.1 新建RedisClient类
@Configuration
public class RedisClient {
@Resource
private RedisTemplate redisTemplate;
/**
* 删除指定key
*
* @param key
*/
public void del(String key) {
redisTemplate.delete(key);
}
/**
* 给一个指定的 key 值附加过期时间
*
* @param key
* @param time
* @return
*/
public boolean expire(String key, long time) {
return redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
/**
* 根据key 获取过期时间
*
* @param key
* @return
*/
public long getTime(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 根据key 获取过期时间
*
* @param key
* @return
*/
public boolean hasKey(String key) {
return redisTemplate.hasKey(key);
}
/**
* 移除指定key 的过期时间
*
* @param key
* @return
*/
public boolean persist(String key) {
return redisTemplate.boundValueOps(key).persist();
}
//- - - - - - - - - - - - - - - - - - - - - String类型 - - - - - - - - - - - - - - - - - - - -
/**
* 根据key获取值
*
* @param key 键
* @return 值
*/
public String get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key).toString();
}
/**
* 将值放入缓存
*
* @param key 键
* @param value 值
* @return true成功 false 失败
*/
public void set(String key, String value) {
redisTemplate.opsForValue().set(key, value);
}
/**
* 将值放入缓存并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒) -1为无期限
* @return true成功 false 失败
*/
public void set(String key, String value, long time) {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
redisTemplate.opsForValue().set(key, value);
}
}
/**
* 将值放入缓存并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒) -1为无期限
* @param timeUnit 时间类型
* @return true成功 false 失败
*/
public void set(String key, String value, long time,TimeUnit timeUnit) {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, timeUnit);
} else {
redisTemplate.opsForValue().set(key, value);
}
}
/**
* 批量添加 key (重复的键会覆盖)
*
* @param keyAndValue
*/
public void batchSet(Map<String, String> keyAndValue) {
redisTemplate.opsForValue().multiSet(keyAndValue);
}
/**
* 批量添加 key-value 只有在键不存在时,才添加
* map 中只要有一个key存在,则全部不添加
*
* @param keyAndValue
*/
public void batchSetIfAbsent(Map<String, String> keyAndValue) {
redisTemplate.opsForValue().multiSetIfAbsent(keyAndValue);
}
/**
* 对一个 key-value 的值进行加减操作,
* 如果该 key 不存在 将创建一个key 并赋值该 number
* 如果 key 存在,但 value 不是长整型 ,将报错
*
* @param key
* @param number
*/
public Long increment(String key, long number) {
return redisTemplate.opsForValue().increment(key, number);
}
/**
* 对一个 key-value 的值进行加减操作,
* 如果该 key 不存在 将创建一个key 并赋值该 number
* 如果 key 存在,但 value 不是 纯数字 ,将报错
*
* @param key
* @param number
*/
public Double increment(String key, double number) {
return redisTemplate.opsForValue().increment(key, number);
}
//- - - - - - - - - - - - - - - - - - - - - set类型 - - - - - - - - - - - - - - - - - - - -
/**
* 将数据放入set缓存
*
* @param key 键
* @return
*/
public void sSet(String key, String value) {
redisTemplate.opsForSet().add(key, value);
}
/**
* 获取变量中的值
*
* @param key 键
* @return
*/
public Set<Object> members(String key) {
return redisTemplate.opsForSet().members(key);
}
/**
* 随机获取变量中指定个数的元素
*
* @param key 键
* @param count 值
* @return
*/
public void randomMembers(String key, long count) {
redisTemplate.opsForSet().randomMembers(key, count);
}
/**
* 随机获取变量中的元素
*
* @param key 键
* @return
*/
public Object randomMember(String key) {
return redisTemplate.opsForSet().randomMember(key);
}
/**
* 弹出变量中的元素
*
* @param key 键
* @return
*/
public Object pop(String key) {
return redisTemplate.opsForSet().pop(key);
}
/**
* 获取变量中值的长度
*
* @param key 键
* @return
*/
public long size(String key) {
return redisTemplate.opsForSet().size(key);
}
/**
* 根据value从一个set中查询,是否存在
*
* @param key 键
* @param value 值
* @return true 存在 false不存在
*/
public boolean sHasKey(String key, Object value) {
return redisTemplate.opsForSet().isMember(key, value);
}
/**
* 检查给定的元素是否在变量中。
*
* @param key 键
* @param obj 元素对象
* @return
*/
public boolean isMember(String key, Object obj) {
return redisTemplate.opsForSet().isMember(key, obj);
}
/**
* 转移变量的元素值到目的变量。
*
* @param key 键
* @param value 元素对象
* @param destKey 元素对象
* @return
*/
public boolean move(String key, String value, String destKey) {
return redisTemplate.opsForSet().move(key, value, destKey);
}
/**
* 批量移除set缓存中元素
*
* @param key 键
* @param values 值
* @return
*/
public void remove(String key, Object... values) {
redisTemplate.opsForSet().remove(key, values);
}
/**
* 通过给定的key求2个set变量的差值
*
* @param key 键
* @param destKey 键
* @return
*/
public Set<Set> difference(String key, String destKey) {
return redisTemplate.opsForSet().difference(key, destKey);
}
//- - - - - - - - - - - - - - - - - - - - - hash类型 - - - - - - - - - - - - - - - - - - - -
/**
* 加入缓存
*
* @param key 键
* @param map 键
* @return
*/
public void add(String key, Map<String, String> map) {
redisTemplate.opsForHash().putAll(key, map);
}
/**
* 获取 key 下的 所有 hashkey 和 value
*
* @param key 键
* @return
*/
public Map<Object, Object> getHashEntries(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* 验证指定 key 下 有没有指定的 hashkey
*
* @param key
* @param hashKey
* @return
*/
public boolean hashKey(String key, String hashKey) {
return redisTemplate.opsForHash().hasKey(key, hashKey);
}
/**
* 获取指定key的值string
*
* @param key 键
* @param key2 键
* @return
*/
public String getMapString(String key, String key2) {
return redisTemplate.opsForHash().get(key, key2).toString();
}
/**
* 获取指定的值Int
*
* @param key 键
* @param key2 键
* @return
*/
public Integer getMapInt(String key, String key2) {
return (Integer) redisTemplate.opsForHash().get(key, key2);
}
/**
* 弹出元素并删除
*
* @param key 键
* @return
*/
public String popValue(String key) {
return redisTemplate.opsForSet().pop(key).toString();
}
/**
* 删除指定 hash 的 HashKey
*
* @param key
* @param hashKeys
* @return 删除成功的 数量
*/
public Long hdel(String key, String... hashKeys) {
return redisTemplate.opsForHash().delete(key, hashKeys);
}
/**
* 给指定 hash 的 hashkey 做增减操作
*
* @param key
* @param hashKey
* @param number
* @return
*/
public Long increment(String key, String hashKey, long number) {
return redisTemplate.opsForHash().increment(key, hashKey, number);
}
/**
* 给指定 hash 的 hashkey 做增减操作
*
* @param key
* @param hashKey
* @param number
* @return
*/
public Double increment(String key, String hashKey, Double number) {
return redisTemplate.opsForHash().increment(key, hashKey, number);
}
/**
* 获取 key 下的 所有 hashkey 字段
*
* @param key
* @return
*/
public Set<Object> hashKeys(String key) {
return redisTemplate.opsForHash().keys(key);
}
/**
* 获取指定 hash 下面的 键值对 数量
*
* @param key
* @return
*/
public Long hashSize(String key) {
return redisTemplate.opsForHash().size(key);
}
//- - - - - - - - - - - - - - - - - - - - - list类型 - - - - - - - - - - - - - - - - - - - -
/**
* 在变量左边添加元素值
*
* @param key
* @param value
* @return
*/
public void leftPush(String key, Object value) {
redisTemplate.opsForList().leftPush(key, value);
}
/**
* 获取集合指定位置的值。
*
* @param key
* @param index
* @return
*/
public Object index(String key, long index) {
return redisTemplate.opsForList().index(key, index);
}
/**
* 获取指定区间的值。
*
* @param key
* @param start
* @param end
* @return
*/
public List<Object> range(String key, long start, long end) {
return redisTemplate.opsForList().range(key, start, end);
}
/**
* 把最后一个参数值放到指定集合的第一个出现中间参数的前面,
* 如果中间参数值存在的话。
*
* @param key
* @param pivot
* @param value
* @return
*/
public void leftPush(String key, String pivot, String value) {
redisTemplate.opsForList().leftPush(key, pivot, value);
}
/**
* 向左边批量添加参数元素。
*
* @param key
* @param values
* @return
*/
public void leftPushAll(String key, String... values) {
// redisTemplate.opsForList().leftPushAll(key,"w","x","y");
redisTemplate.opsForList().leftPushAll(key, values);
}
/**
* 向集合最右边添加元素。
*
* @param key
* @param value
* @return
*/
public void leftPushAll(String key, String value) {
redisTemplate.opsForList().rightPush(key, value);
}
/**
* 向左边批量添加参数元素。
*
* @param key
* @param values
* @return
*/
public void rightPushAll(String key, String... values) {
//redisTemplate.opsForList().leftPushAll(key,"w","x","y");
redisTemplate.opsForList().rightPushAll(key, values);
}
/**
* 向已存在的集合中添加元素。
*
* @param key
* @param value
* @return
*/
public void rightPushIfPresent(String key, Object value) {
redisTemplate.opsForList().rightPushIfPresent(key, value);
}
/**
* 向已存在的集合中添加元素。
*
* @param key
* @return
*/
public long listLength(String key) {
return redisTemplate.opsForList().size(key);
}
/**
* 移除集合中的左边第一个元素。
*
* @param key
* @return
*/
public void leftPop(String key) {
redisTemplate.opsForList().leftPop(key);
}
/**
* 移除集合中左边的元素在等待的时间里,如果超过等待的时间仍没有元素则退出。
*
* @param key
* @return
*/
public void leftPop(String key, long timeout, TimeUnit unit) {
redisTemplate.opsForList().leftPop(key, timeout, unit);
}
/**
* 移除集合中右边的元素。
*
* @param key
* @return
*/
public void rightPop(String key) {
redisTemplate.opsForList().rightPop(key);
}
/**
* 移除集合中右边的元素在等待的时间里,如果超过等待的时间仍没有元素则退出。
*
* @param key
* @return
*/
public void rightPop(String key, long timeout, TimeUnit unit) {
redisTemplate.opsForList().rightPop(key, timeout, unit);
}
}
3.7.1 添加类路径到spring.factories文件中
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.xiaoniu.redisson.config.RedissonAutoConfiguration,\
com.xiaoniu.redisson.client.RedisClient
四、使用方法
1、先打成jar包
2、在其他项目中引入依赖
3、在项目application.yaml文件中添加redis配置
spring:
#Redis相关配置
redis:
host: 127.0.0.1
port: 6379
dataBase: 0
maxActive: 10 #最大连接数
maxIdle: 10 #连接池最大空闲连接
maxWait: 10000 #连接池最大阻塞等待时间(使用负值表示没有限制)
min-idle: 0 #连接池最小空闲连接
timeout: 1000 #超时时间
4、在类中注入属性
说明:这种方式是直接使用封装好的redis工具类
5、或者在类中注入属性
说明:这种方式注入需要自定义调用redis的方法
步骤4、5选择任意一种即可,如有需要两种可以同时选择