SpringBoot如何封裝自己的SDK
1. 前言
在使用Maven構(gòu)建項(xiàng)目時(shí),會(huì)在pom.xml文件中引入各種各樣的依賴,那么我們?nèi)绾螌⒆约撼S玫囊恍┕ぞ哳悗?kù)進(jìn)行封裝成starter或者SDK供其他項(xiàng)目使用呢,本博客就會(huì)帶著大家一步一步創(chuàng)建自定義的SDK依賴。
2.項(xiàng)目準(zhǔn)備
我們可以在原有項(xiàng)目上進(jìn)行修改或者重新創(chuàng)建對(duì)應(yīng)的項(xiàng)目。
2.1 創(chuàng)建項(xiàng)目(封裝redis為例)
此處使用IDEA內(nèi)置Spring Initializr初始化工具快速創(chuàng)建項(xiàng)目:
填寫(xiě)項(xiàng)目配置:

點(diǎn)擊下一步
設(shè)置SpringBoot版本以及依賴

此處一定要勾選(Spring Configuration Processor依賴),這樣當(dāng)我們使用依賴后,可在application.yml中看到提示

點(diǎn)擊create創(chuàng)建項(xiàng)目即可!
2.1.1刪除Maven的build插件

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.5.3</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.common.redis.sdk</groupId> <artifactId>common-redis-sdk</artifactId> <version>0.0.1</version> <name>common-redis-sdk</name> <description>common-redis-sdk</description> <url/> <licenses> <license/> </licenses> <developers> <developer/> </developers> <scm> <connection/> <developerConnection/> <tag/> <url/> </scm> <properties> <java.version>17</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- SpringBoot Boot Redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version> 3.5.3</version> </dependency> <!-- Alibaba Fastjson --> <dependency> <groupId>com.alibaba.fastjson2</groupId> <artifactId>fastjson2</artifactId> <version> 2.0.53</version> </dependency> </dependencies> </project>
2.1.2刪除啟動(dòng)類
由于這不是一個(gè)Web項(xiàng)目,因此我們需要將啟動(dòng)類給刪除
2.1.3 編寫(xiě)配置類
package com.common.redis.sdk.configure;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* redis配置
*/
@Configuration
@EnableCaching
@AutoConfigureBefore(RedisAutoConfiguration.class)
@SuppressWarnings("deprecation")
public class RedisConfig extends CachingConfigurerSupport {
@Bean
@SuppressWarnings(value = {"unchecked", "rawtypes"})
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);
// 使用StringRedisSerializer來(lái)序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(serializer);
// Hash的key也采用StringRedisSerializer的序列化方式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(serializer);
template.afterPropertiesSet();
return template;
}
}2.1.3 編寫(xiě)工具類
package com.common.redis.sdk.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* spring redis 工具類
*
**/
@SuppressWarnings(value = {"unchecked", "rawtypes"})
@Component
public class RedisService {
@Autowired
public RedisTemplate redisTemplate;
/**
* 緩存基本的對(duì)象,Integer、String、實(shí)體類等
*
* @param key 緩存的鍵值
* @param value 緩存的值
*/
public <T> void setCacheObject(final String key, final T value) {
redisTemplate.opsForValue().set(key, value);
}
/**
* 緩存基本的對(duì)象,Integer、String、實(shí)體類等
*
* @param key 緩存的鍵值
* @param value 緩存的值
* @param timeout 時(shí)間
* @param timeUnit 時(shí)間顆粒度
*/
public <T> void setCacheObject(final String key, final T value, final Long timeout, final TimeUnit timeUnit) {
redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
}
/**
* 設(shè)置有效時(shí)間
*
* @param key Redis鍵
* @param timeout 超時(shí)時(shí)間
* @return true=設(shè)置成功;false=設(shè)置失敗
*/
public boolean expire(final String key, final long timeout) {
return expire(key, timeout, TimeUnit.SECONDS);
}
/**
* 設(shè)置有效時(shí)間
*
* @param key Redis鍵
* @param timeout 超時(shí)時(shí)間
* @param unit 時(shí)間單位
* @return true=設(shè)置成功;false=設(shè)置失敗
*/
public boolean expire(final String key, final long timeout, final TimeUnit unit) {
return redisTemplate.expire(key, timeout, unit);
}
/**
* 獲取有效時(shí)間
*
* @param key Redis鍵
* @return 有效時(shí)間
*/
public long getExpire(final String key) {
return redisTemplate.getExpire(key);
}
/**
* 判斷 key是否存在
*
* @param key 鍵
* @return true 存在 false不存在
*/
public Boolean hasKey(String key) {
return redisTemplate.hasKey(key);
}
/**
* 獲得緩存的基本對(duì)象。
*
* @param key 緩存鍵值
* @return 緩存鍵值對(duì)應(yīng)的數(shù)據(jù)
*/
public <T> T getCacheObject(final String key) {
ValueOperations<String, T> operation = redisTemplate.opsForValue();
return operation.get(key);
}
/**
* 刪除單個(gè)對(duì)象
*
* @param key
*/
public boolean deleteObject(final String key) {
return redisTemplate.delete(key);
}
/**
* 刪除集合對(duì)象
*
* @param collection 多個(gè)對(duì)象
* @return
*/
public boolean deleteObject(final Collection collection) {
return redisTemplate.delete(collection) > 0;
}
/**
* 緩存List數(shù)據(jù)
*
* @param key 緩存的鍵值
* @param dataList 待緩存的List數(shù)據(jù)
* @return 緩存的對(duì)象
*/
public <T> long setCacheList(final String key, final List<T> dataList) {
Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
return count == null ? 0 : count;
}
/**
* 獲得緩存的list對(duì)象
*
* @param key 緩存的鍵值
* @return 緩存鍵值對(duì)應(yīng)的數(shù)據(jù)
*/
public <T> List<T> getCacheList(final String key) {
return redisTemplate.opsForList().range(key, 0, -1);
}
/**
* 緩存Set
*
* @param key 緩存鍵值
* @param dataSet 緩存的數(shù)據(jù)
* @return 緩存數(shù)據(jù)的對(duì)象
*/
public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet) {
BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
Iterator<T> it = dataSet.iterator();
while (it.hasNext()) {
setOperation.add(it.next());
}
return setOperation;
}
/**
* 獲得緩存的set
*
* @param key
* @return
*/
public <T> Set<T> getCacheSet(final String key) {
return redisTemplate.opsForSet().members(key);
}
/**
* 緩存Map
*
* @param key
* @param dataMap
*/
public <T> void setCacheMap(final String key, final Map<String, T> dataMap) {
if (dataMap != null) {
redisTemplate.opsForHash().putAll(key, dataMap);
}
}
/**
* 獲得緩存的Map
*
* @param key
* @return
*/
public <T> Map<String, T> getCacheMap(final String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* 往Hash中存入數(shù)據(jù)
*
* @param key Redis鍵
* @param hKey Hash鍵
* @param value 值
*/
public <T> void setCacheMapValue(final String key, final String hKey, final T value) {
redisTemplate.opsForHash().put(key, hKey, value);
}
/**
* 獲取Hash中的數(shù)據(jù)
*
* @param key Redis鍵
* @param hKey Hash鍵
* @return Hash中的對(duì)象
*/
public <T> T getCacheMapValue(final String key, final String hKey) {
HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
return opsForHash.get(key, hKey);
}
/**
* 獲取多個(gè)Hash中的數(shù)據(jù)
*
* @param key Redis鍵
* @param hKeys Hash鍵集合
* @return Hash對(duì)象集合
*/
public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys) {
return redisTemplate.opsForHash().multiGet(key, hKeys);
}
/**
* 刪除Hash中的某條數(shù)據(jù)
*
* @param key Redis鍵
* @param hKey Hash鍵
* @return 是否成功
*/
public boolean deleteCacheMapValue(final String key, final String hKey) {
return redisTemplate.opsForHash().delete(key, hKey) > 0;
}
/**
* 獲得緩存的基本對(duì)象列表
*
* @param pattern 字符串前綴
* @return 對(duì)象列表
*/
public Collection<String> keys(final String pattern) {
return redisTemplate.keys(pattern);
}
}2.1.4 自動(dòng)配置機(jī)制文件配置
- 在 resources目錄下創(chuàng)建META-INF/spring兩級(jí)子目錄
- 然后在spring目錄下創(chuàng)建文件名為org.springframework.boot.autoconfigure.AutoConfiguration.imports的文件,如果配置無(wú)誤應(yīng)該在IDEA中會(huì)有識(shí)別提示:

org.springframework.boot.autoconfigure.AutoConfiguration.imports
是 Spring Boot 的一種自動(dòng)配置機(jī)制,它允許你在 Spring Boot 的自動(dòng)配置類中通過(guò) @Import 注解動(dòng)態(tài)地導(dǎo)入其他類。這種機(jī)制通常用于為 Spring Boot 應(yīng)用程序自動(dòng)裝配額外的配置或依賴。

- 在org.springframework.boot.autoconfigure.AutoConfiguration.imports文件中配置項(xiàng)目配置類的路徑
com.common.redis.sdk.configure.RedisConfig com.common.redis.sdk.service.RedisService
2.1.5 使用Maven構(gòu)建成Jar包


2.2 原有項(xiàng)目改造(參考自建項(xiàng)目)
2.2.1 刪除maven的build插件
2.2.2 刪除啟動(dòng)類
2.2.3 自動(dòng)配置機(jī)制文件配置
2.2.4 使用maven構(gòu)建jar包
在項(xiàng)目中使用
將本地jar打進(jìn)maven倉(cāng)庫(kù)中
注釋:
-Dfile=jar文件所在路徑
-DgroupId=包名
-DartifactId=項(xiàng)目名
-Dversion=版本號(hào)
-Dpackaging=jar
mvn install:install-file -Dfile=F:\twj\code\code\common-redis-sdk\target\common-redis-sdk-0.0.1.jar -DgroupId=com.common.redis.sdk -DartifactId=common-redis-sdk -Dversion=0.0.1 -Dpackaging=jar
導(dǎo)入依賴
<dependency>
<groupId>com.common.redis.sdk</groupId>
<artifactId>common-redis-sdk</artifactId>
<version>0.0.1</version>
</dependency>配置類中變量配置
在引入jar包的項(xiàng)目的配置文件中進(jìn)行參數(shù)配置
假設(shè)我們的配置類如下:
@Configuration
@ConfigurationProperties("sicheng.database")
@Data
@ComponentScan
public class sqlSessionConfig{
private String userName;
private String password;
private String driver;
private String url;
@Bean
public sqlSessionFactory getSqlSessionFactory() {
return new sqlSessionFactory(userName,password,driver,url);
}
}我們?cè)陧?xiàng)目的application.yml文件中就需要進(jìn)行如下配置
sicheng:
database:
driver: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/sicheng
username: root
password: 123456在項(xiàng)目中使用common-redis-sdk
在項(xiàng)目application.yml文件中填寫(xiě)redis鏈接信息
spring:
data:
redis:
host: localhost
port: 13337
password: password
database: 10
timeout: 6000
lettuce:
pool:
max-active: 10 # 連接池最大連接數(shù)(使用負(fù)值表示沒(méi)有限制),如果賦值為-1,則表示不限制;如果pool已經(jīng)分配了maxActive個(gè)jedis實(shí)例,則此時(shí)pool的狀態(tài)為exhausted(耗盡)
max-idle: 8 # 連接池中的最大空閑連接 ,默認(rèn)值也是8
max-wait: 100 # # 等待可用連接的最大時(shí)間,單位毫秒,默認(rèn)值為-1,表示永不超時(shí)。如果超過(guò)等待時(shí)間,則直接拋出JedisConnectionException
min-idle: 2 # 連接池中的最小空閑連接 ,默認(rèn)值也是0
shutdown-timeout: 100ms在具體類中進(jìn)行使用

到此這篇關(guān)于SpringBoot封裝自己的SDK的文章就介紹到這了,更多相關(guān)SpringBoot封裝SDK內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Springboot實(shí)現(xiàn)驗(yàn)證碼登錄
這篇文章主要為大家詳細(xì)介紹了Springboot實(shí)現(xiàn)驗(yàn)證碼登錄,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-07-07
java構(gòu)建OAuth2授權(quán)服務(wù)器
本文主要介紹了java構(gòu)建OAuth2授權(quán)服務(wù)器,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-07-07
java中volatile不能保證線程安全(實(shí)例講解)
下面小編就為大家?guī)?lái)一篇java中volatile不能保證線程安全(實(shí)例講解)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-09-09
Springboot中spring-boot-starter-quartz的使用及說(shuō)明
這篇文章主要介紹了Springboot中spring-boot-starter-quartz的使用及說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12
SWT(JFace)體驗(yàn)之ApplicationWindow
SWT(JFace)體驗(yàn)之ApplicationWindow2009-06-06
MP(MyBatis-Plus)實(shí)現(xiàn)樂(lè)觀鎖更新功能的示例代碼
這篇文章主要介紹了MP(MyBatis-Plus)實(shí)現(xiàn)樂(lè)觀鎖更新功能的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
spring security獲取用戶信息的實(shí)現(xiàn)代碼
這篇文章主要介紹了spring security獲取用戶信息的實(shí)現(xiàn)代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12
IDEA JeeSite框架httpSession.invalidate()無(wú)效問(wèn)題解決方案
這篇文章主要介紹了IDEA JeeSite框架httpSession.invalidate()無(wú)效問(wèn)題解決方案,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09
解析Oracle數(shù)據(jù)庫(kù)中的對(duì)象集合schema
這篇文章主要介紹了Oracle數(shù)據(jù)庫(kù)中的對(duì)象集合schema,是Oracle數(shù)據(jù)庫(kù)入門學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-11-11

