欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot如何封裝自己的SDK

 更新時(shí)間:2025年07月15日 09:38:50   作者:twj_one  
在使用Maven構(gòu)建項(xiàng)目時(shí),會(huì)在pom.xml文件中引入各種各樣的依賴,那么我們?nèi)绾螌⒆约撼S玫囊恍┕ぞ哳悗?kù)進(jìn)行封裝成starter或者SDK供其他項(xiàng)目使用呢,本文帶著大家一步一步創(chuàng)建自定義的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ī)制文件配置

  1. 在 resources目錄下創(chuàng)建META-INF/spring兩級(jí)子目錄
  2. 然后在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)裝配額外的配置或依賴。

  1. 在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)文章

最新評(píng)論