91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

SpringBoot如何實現ApplicationEvent事件的監聽與發布

發布時間:2023-03-09 10:09:03 來源:億速云 閱讀:149 作者:iii 欄目:開發技術

這篇文章主要介紹“SpringBoot如何實現ApplicationEvent事件的監聽與發布”,在日常操作中,相信很多人在SpringBoot如何實現ApplicationEvent事件的監聽與發布問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”SpringBoot如何實現ApplicationEvent事件的監聽與發布”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

通過發布訂閱模式實現數據的異步處理,比如異步處理郵件發送

新建SpringBoot項目

項目結構

.
├── pom.xml
└── src
    └── main
        ├── java
        │   └── com
        │       └── example
        │           └── demo
        │               ├── Application.java
        │               ├── config
        │               │   └── TaskPoolConfig.java
        │               ├── controller
        │               │   └── IndexController.java
        │               ├── entity
        │               │   └── EmailDto.java
        │               ├── event
        │               │   └── SendEmailEvent.java
        │               ├── listener
        │               │   └── SendEmailListener.java
        │               └── service
        │                   ├── SendEmailService.java
        │                   └── impl
        │                       └── SendEmailServiceImpl.java
        └── resources
            ├── application.yml
            ├── static
            └── templates

實現代碼

pom.xml

<?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>2.7.7</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <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>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Application.java

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

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

TaskPoolConfig.java

package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;


/**
 * 線程池參數配置
 **/
@EnableAsync
@Configuration
public class TaskPoolConfig {
    /**
     * 自定義線程池
     **/
    @Bean
    public Executor taskExecutor() {
        //返回可用處理器的Java虛擬機的數量 12
        int i = Runtime.getRuntime().availableProcessors();
        System.out.println("系統最大線程數  : " + i);

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心線程池大小
        executor.setCorePoolSize(16);
        //最大線程數
        executor.setMaxPoolSize(20);
        //配置隊列容量,默認值為Integer.MAX_VALUE
        executor.setQueueCapacity(99999);
        //活躍時間
        executor.setKeepAliveSeconds(60);
        //線程名字前綴
        executor.setThreadNamePrefix("asyncServiceExecutor -");
        //設置此執行程序應該在關閉時阻止的最大秒數,以便在容器的其余部分繼續關閉之前等待剩余的任務完成他們的執行
        executor.setAwaitTerminationSeconds(60);
        //等待所有的任務結束后再關閉線程池
        executor.setWaitForTasksToCompleteOnShutdown(true);

        return executor;
    }
}

EmailDto.java

package com.example.demo.entity;

import lombok.Data;

@Data
public class EmailDto {
    private String email;
    private String subject;
    private String content;
}

SendEmailEvent.java

package com.example.demo.event;

import com.example.demo.entity.EmailDto;
import org.springframework.context.ApplicationEvent;

/**
 * 自定義事件
 */
public class SendEmailEvent extends ApplicationEvent {
    private EmailDto emailDto;

    public SendEmailEvent(EmailDto emailDto) {
        super(emailDto);
        this.emailDto = emailDto;
    }

    public EmailDto getEmailDto() {
        return this.emailDto;
    }
}

SendEmailListener.java

package com.example.demo.listener;

import com.example.demo.entity.EmailDto;
import com.example.demo.event.SendEmailEvent;
import com.example.demo.service.SendEmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * 事件監聽器
 */
@Component
public class SendEmailListener implements ApplicationListener<SendEmailEvent> {
    @Autowired
    private SendEmailService sendEmailService;

    @Async
    @Override
    public void onApplicationEvent(SendEmailEvent event) {
        EmailDto emailDto = event.getEmailDto();
        this.sendEmailService.sendEmail(emailDto);
    }
}

SendEmailService.java

package com.example.demo.service;

import com.example.demo.entity.EmailDto;

public interface SendEmailService {
    void sendEmail(EmailDto emailDto);
}

SendEmailServiceImpl.java

package com.example.demo.service.impl;

import com.example.demo.entity.EmailDto;
import com.example.demo.service.SendEmailService;
import org.springframework.stereotype.Service;

@Service
public class SendEmailServiceImpl implements SendEmailService {
    @Override
    public void sendEmail(EmailDto emailDto) {
        try {
            // 模擬耗時3秒
            Thread.sleep(3 * 1000);
        } catch (Exception e) {
            System.out.println("Email發送異常");
        }

        System.out.println("Email發送成功 " + emailDto);
    }
}

IndexController.java

package com.example.demo.controller;

import com.example.demo.entity.EmailDto;
import com.example.demo.event.SendEmailEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class IndexController {
    @Autowired
    private ApplicationEventPublisher publisher;

    @GetMapping("/sendEmail")
    public String sendEmail() {
        EmailDto emailDto = new EmailDto();
        emailDto.setEmail("tom@qq.com");
        emailDto.setSubject("郵件標題");
        emailDto.setContent("郵件內容");

        // 發布事件
        publisher.publishEvent(new SendEmailEvent(emailDto));
        return "success";
    }
}

到此,關于“SpringBoot如何實現ApplicationEvent事件的監聽與發布”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

余姚市| 芦山县| 高青县| 宣恩县| 赤水市| 息烽县| 富阳市| 视频| 始兴县| 都匀市| 新津县| 门源| 平果县| 卓尼县| 呼伦贝尔市| 绥芬河市| 柳州市| 北海市| 龙门县| 阿拉善盟| 威宁| 桂阳县| 富蕴县| 侯马市| 互助| 六盘水市| 广饶县| 葫芦岛市| 杭锦后旗| 沙雅县| 广宗县| 合川市| 冷水江市| 尖扎县| 惠安县| 会宁县| 定结县| 句容市| 澄江县| 秀山| 泽库县|