日韩成人免费在线_国产成人一二_精品国产免费人成电影在线观..._日本一区二区三区久久久久久久久不

當前位置:首頁 > 科技  > 軟件

SpringBoot3進階用法,你學會了嗎?

來源: 責編: 時間:2023-08-09 23:02:58 372觀看
導讀一、簡介在上篇《SpringBoot3基礎》中已經完成入門案例的開發和測試,在這篇內容中再來看看進階功能的用法;主要涉及如下幾個功能點:調度任務:在應用中提供一定的輕量級的調度能力,比如方法按指定的定時規則執行,或者異步執

一、簡介

在上篇《SpringBoot3基礎》中已經完成入門案例的開發和測試,在這篇內容中再來看看進階功能的用法;24D28資訊網——每日最新資訊28at.com

主要涉及如下幾個功能點:24D28資訊網——每日最新資訊28at.com

調度任務:在應用中提供一定的輕量級的調度能力,比如方法按指定的定時規則執行,或者異步執行,從而完成相應的代碼邏輯;24D28資訊網——每日最新資訊28at.com

郵件發送:郵件作為消息體系中的渠道,是常用的功能;24D28資訊網——每日最新資訊28at.com

應用監控:實時或定期監控應用的健康狀態,以及各種關鍵的指標信息;24D28資訊網——每日最新資訊28at.com

切面編程:通過預編譯方式和運行期動態代理實現程序中部分功能統一維護的技術,可以將業務流程中的部分邏輯解耦處理,提升可復用性;24D28資訊網——每日最新資訊28at.com

二、工程搭建

1、工程結構

圖片圖片24D28資訊網——每日最新資訊28at.com

2、依賴管理

<!-- 基礎框架依賴 --><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-web</artifactId>    <version>${spring-boot.version}</version></dependency><!-- 應用監控組件 --><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-actuator</artifactId>    <version>${spring-boot.version}</version></dependency><!-- 切面編程組件 --><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-aop</artifactId>    <version>${spring-boot.version}</version></dependency><!-- 郵件發送組件 --><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-mail</artifactId>    <version>${spring-boot.version}</version></dependency>

這里再細致的查看一下各個功能的組件依賴體系,SpringBoot只是提供了強大的集成能力;24D28資訊網——每日最新資訊28at.com

圖片圖片24D28資訊網——每日最新資訊28at.com

3、啟動類

注意在啟動類中使用注解開啟了異步EnableAsync和調度EnableScheduling的能力;24D28資訊網——每日最新資訊28at.com

@EnableAsync@EnableScheduling@SpringBootApplicationpublic class Application {    public static void main(String[] args) {        SpringApplication.run(Application.class, args);    }}

三、切面編程

1、定義注解

定義一個方法級的注解;24D28資訊網——每日最新資訊28at.com

@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)@Documentedpublic @interface DefAop {    /**     * 模塊描述     */    String modelDesc();    /**     * 其他信息     */    String otherInfo();}

2、注解切面

在切面中使用Around環繞通知類型,會攔截到DefAop注解標記的方法,然后解析獲取各種信息,進而嵌入自定義的流程邏輯;24D28資訊網——每日最新資訊28at.com

@Component@Aspectpublic class LogicAop {    private static final Logger logger = LoggerFactory.getLogger(LogicAop.class) ;        /**     * 切入點     */    @Pointcut("@annotation(com.boot.senior.aop.DefAop)")    public void defAopPointCut() {    }    /**     * 環繞切入     */    @Around("defAopPointCut()")    public Object around (ProceedingJoinPoint proceedingJoinPoint) throws Throwable {        Object result = null ;        try{            // 執行方法            result = proceedingJoinPoint.proceed();        } catch (Exception e){            e.printStackTrace();        } finally {            // 處理邏輯            buildLogicAop(proceedingJoinPoint) ;        }        return result ;    }    /**     * 構建處理邏輯     */    private void buildLogicAop (ProceedingJoinPoint point){        // 獲取方法        MethodSignature signature = (MethodSignature) point.getSignature();        Method reqMethod = signature.getMethod();        // 獲取注解        DefAop defAop = reqMethod.getAnnotation(DefAop.class);        String modelDesc = defAop.modelDesc() ;        String otherInfo = defAop.otherInfo();        logger.info("DefAop-modelDesc:{}",modelDesc);        logger.info("DefAop-otherInfo:{}",otherInfo);    }}

四、調度任務

1、異步處理

1.1 方法定義

通過Async注解標識兩個方法,方法在執行時會休眠10秒,其中一個注解指定異步執行使用asyncPool線程池;24D28資訊網——每日最新資訊28at.com

@Servicepublic class AsyncService {    private static final Logger log = LoggerFactory.getLogger(AsyncService.class);    @Async    public void asyncJob (){        try {            TimeUnit.SECONDS.sleep(10);        } catch (InterruptedException e) {            throw new RuntimeException(e);        }        log.info("async-job-01-end...");    }    @Async("asyncPool")    public void asyncJobPool (){        try {            TimeUnit.SECONDS.sleep(10);        } catch (InterruptedException e) {            throw new RuntimeException(e);        }        log.info("async-job-02-end...");    }}

1.2 線程池

定義一個ThreadPoolTaskExecutor線程池對象;24D28資訊網——每日最新資訊28at.com

@Configurationpublic class PoolConfig {    @Bean("asyncPool")    public Executor asyncPool () {        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();        // 線程池命名前綴        executor.setThreadNamePrefix("async-pool-");        // 核心線程數5        executor.setCorePoolSize(5);        // 最大線程數10        executor.setMaxPoolSize(10);        // 緩沖執行任務的隊列50        executor.setQueueCapacity(50);        // 線程的空閑時間60秒        executor.setKeepAliveSeconds(60);        // 線程池對拒絕任務的處理策略        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());        // 線程池關閉的時等待所有任務都完成再繼續銷毀其他的Bean        executor.setWaitForTasksToCompleteOnShutdown(true);        // 設置線程池中任務的等待時間        executor.setAwaitTerminationSeconds(300);        return executor;    }}

1.3 輸出信息

從輸出的日志信息中可以發現,兩個異步方法所使用的線程池不一樣,asyncJob采用默認的cTaskExecutor線程池,asyncJobPool方法采用的是async-pool線程池;24D28資訊網——每日最新資訊28at.com

[schedule-pool-1] c.boot.senior.schedule.ScheduleService   : async-job-02-end...[cTaskExecutor-1] c.boot.senior.schedule.ScheduleService   : async-job-01-end...

2、調度任務

2.1 調度配置

通過實現SchedulingConfigurer接口,來修改調度任務的配置,這里重新定義任務執行的線程池;24D28資訊網——每日最新資訊28at.com

@Configurationpublic class ScheduleConfig implements SchedulingConfigurer {    @Override    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {        scheduledTaskRegistrar.setScheduler(Executors.newScheduledThreadPool(5));    }}

2.2 調度方法

通過Scheduled注解來標記方法,基于定時器的規則設定,來統一管理方法的執行時間;24D28資訊網——每日最新資訊28at.com

@Componentpublic class ScheduleJob {    private static final Logger log = LoggerFactory.getLogger(ScheduleJob.class);    private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;    /**     * 上一次開始執行時間點之后10秒再執行     */    @Scheduled(fixedRate = 10000)    private void timerJob1(){        log.info("timer-job-1:{}",format.format(new Date()));    }    /**     * 上一次執行完畢時間點之后10秒再執行     */    @Scheduled(fixedDelay = 10000)    private void timerJob2(){        log.info("timer-job-2:{}",format.format(new Date()));    }    /**     * Cron表達式:每30秒執行一次     */    @Scheduled(cron = "0/30 * * * * ?")    private void timerJob3(){        log.info("timer-job-3:{}",format.format(new Date()));    }}

五、郵件發送

1、郵件配置

采用QQ郵箱來模擬郵件的發送方,需要先開啟smtp郵件傳輸協議,在QQ郵箱的設置/賬戶路徑下,并且獲取相應的授權碼,在項目的配置中使用;24D28資訊網——每日最新資訊28at.com

圖片24D28資訊網——每日最新資訊28at.com

spring:  application:    name: boot-senior  # 郵件配置  mail:    host: smtp.qq.com    port: 465    protocol: smtps    username: 郵箱賬號    password: 郵箱授權碼    properties:      mail.smtp.ssl.enable: true

2、方法封裝

定義一個簡單的郵件發送方法,并且可以添加附件,是常用的功能之一;另外也可以通過Html靜態頁渲染,再轉換為郵件內容的方式;24D28資訊網——每日最新資訊28at.com

@Servicepublic class SendMailService {    @Value("${spring.mail.username}")    private String userName ;    @Resource    private JavaMailSender sender;    /**     * 帶附件的郵件發送方法     * @param toUsers 接收人     * @param subject 主題     * @param content 內容     * @param attachPath 附件地址     * @return java.lang.String     * @since 2023-07-10 17:03     */    public String sendMail (String[] toUsers,String subject,                            String content,String attachPath) throws Exception {        // MIME郵件類        MimeMessage mimeMessage = sender.createMimeMessage();        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);        // 郵件發送方From和接收方To        helper.setFrom(userName);        helper.setTo(toUsers);        // 郵件主題和內容        helper.setSubject(subject);        helper.setText(content);        // 郵件中的附件        File attachFile = ResourceUtils.getFile(attachPath);        helper.addAttachment(attachFile.getName(), attachFile);        // 執行郵件發送命令        sender.send(mimeMessage);        return "send...mail...sus" ;    }}

測試結果24D28資訊網——每日最新資訊28at.com

圖片圖片24D28資訊網——每日最新資訊28at.com

六、應用監控

1、監控配置

在springboot的actuator組件中,可以通過提供的Rest接口,來獲取應用的監控信息;24D28資訊網——每日最新資訊28at.com

# 應用監控配置management:  endpoints:    web:      exposure:        # 打開所有的監控點        include: "*"      base-path: /monitor  endpoint:    health:      enabled: true      show-details: always    beans:      enabled: true    shutdown:      enabled: true

2、相關接口

2.1 Get類型接口:主機:端口/monitor/health,查看應用的健康信息,三個核心指標:status狀態,diskSpace磁盤空間,ping檢查;24D28資訊網——每日最新資訊28at.com

{    /* 狀態值 */ "status": "UP", "components": {     /* 磁盤空間 */  "diskSpace": {   "status": "UP",   "details": {    "total": 250685575168,    "free": 112149811200,    "threshold": 10485760,    "path": "Path/butte-spring-parent/.",    "exists": true   }  },  /* Ping檢查 */  "ping": {   "status": "UP"  } }}

2.2 Get類型接口:主機:端口/monitor/beans,查看bean列表;24D28資訊網——每日最新資訊28at.com

{ "contexts": {  "boot-senior": {   "beans": {    "asyncPool": {     "scope": "singleton",     "type": "org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor",     "resource": "class path resource [com/boot/senior/schedule/PoolConfig.class]"    },    "asyncService": {     "scope": "singleton",     "type": "com.boot.senior.schedule.AsyncService$$SpringCGLIB$$0"    }   }  } }}

2.3 Post類型接口:主機:端口/monitor/shutdown,關閉應用程序;24D28資訊網——每日最新資訊28at.com

{    "message": "Shutting down, bye..."}

七、參考源碼

文檔倉庫:https://gitee.com/cicadasmile/butte-java-note源碼倉庫:https://gitee.com/cicadasmile/butte-spring-parent

本文鏈接:http://www.www897cc.com/showinfo-26-5154-0.htmlSpringBoot3進階用法,你學會了嗎?

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: SpringBoot整合RabbitMQ延遲隊列&amp;優先級隊列詳解

下一篇: VasDolly服務端打渠道包教程

標簽:
  • 熱門焦點
  • K60 Pro官方停產 第三方瞬間漲價

    雖然沒有官方宣布,但Redmi的一些高管也已經透露了,Redmi K60 Pro已經停產且不會補貨,這一切都是為了即將到來的K60 Ultra鋪路,屬于廠家的正常操作。但有意思的是該機在停產之后
  • 官方承諾:K60至尊版將會首批升級MIUI 15

    全新的MIUI 15今天也有了消息,在官宣了K60至尊版將會搭載天璣9200+處理器和獨顯芯片X7的同時,Redmi給出了官方承諾,K60至尊重大更新首批升級,會首批推送MIUI 15。也就是說雖然
  • Automa-通過連接塊來自動化你的瀏覽器

    1、前言通過瀏覽器插件可實現自動化腳本的錄制與編寫,具有代表性的工具就是:Selenium IDE、Katalon Recorder,對于簡單的業務來說可快速實現自動化的上手工作。Selenium IDEKat
  • 多線程開發帶來的問題與解決方法

    使用多線程主要會帶來以下幾個問題:(一)線程安全問題  線程安全問題指的是在某一線程從開始訪問到結束訪問某一數據期間,該數據被其他的線程所修改,那么對于當前線程而言,該線程
  • 使用Webdriver-manager解決瀏覽器與驅動不匹配所帶來自動化無法執行的問題

    1、前言在我們使用 Selenium 進行 UI 自動化測試時,常常會因為瀏覽器驅動與瀏覽器版本不匹配,而導致自動化測試無法執行,需要手動去下載對應的驅動版本,并替換原有的驅動,可能還
  • 10天營收超1億美元,《星鐵》比《原神》差在哪?

    來源:伯虎財經作者:陳平安即便你沒玩過《原神》,你一定聽說過的它的大名。恨它的人把《原神》開服那天稱作是中國游戲史上最黑暗的一天,有粉絲因為索尼在PS平臺上線《原神》,怒而
  • 網傳小米汽車開始篩選交付中心 建筑面積不低于3000平方米

    7月7日消息,近日有微博網友@長三角行健者爆料稱,據經銷商集團反饋,小米汽車目前已經開始了交付中心的篩選工作,要求候選場地至少有120個車位,建筑不能低
  • 朋友圈可以修改可見范圍了 蘋果用戶可率先體驗

    近日,iOS用戶迎來微信8.0.27正式版更新,除了可更換二維碼背景外,還新增了多項實用功能。在新版微信中,朋友圈終于可以修改可見范圍,簡單來說就是已發布的朋友圈
  • 電博會與軟博會實現"線下+云端"的雙線融合

    在本次“電博會”與“軟博會”雙展會利好條件的加持下,既可以發揮展會拉動人流、信息流、資金流實現快速交互流動的作用,繼而推動區域經濟良性發展;又可以聚
Top 主站蜘蛛池模板: 梅州市| 永兴县| 天峨县| 岳阳市| 凤庆县| 咸丰县| 彭泽县| 江都市| 外汇| 沙湾县| 三都| 宣恩县| 盐边县| 资溪县| 洛隆县| 怀宁县| 信宜市| 深水埗区| 平顶山市| 翁源县| 松潘县| 花莲县| 固镇县| 新蔡县| 长沙县| 沂源县| 仙游县| 衢州市| 平潭县| 白沙| 家居| 凤山县| 新昌县| 铁岭市| 杂多县| 襄樊市| 苏尼特左旗| 米易县| 辽宁省| 亚东县| 保德县|