Spring Boot应用示例

最近更新时间:2022-05-06 17:44:06

查看PDF

1. 添加pom依赖

<properties>
    <spring-boot.version>2.3.2.RELEASE</spring-boot.version>
    <cloudevents.version>2.3.0</cloudevents.version>
  </properties>

 <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-dependencies</artifactId>
        <version>${spring-boot.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <version>${spring-boot.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-jersey</artifactId>
      <version>${spring-boot.version}</version>
    </dependency>
    <dependency>
      <groupId>io.cloudevents</groupId>
      <artifactId>cloudevents-core</artifactId>
      <version>${cloudevents.version}</version>
    </dependency>
    <!-- To use the json format and the cloudevent data mapper -->
    <dependency>
      <groupId>io.cloudevents</groupId>
      <artifactId>cloudevents-json-jackson</artifactId>
      <version>${cloudevents.version}</version>
    </dependency>
    <dependency>
      <groupId>io.cloudevents</groupId>
      <artifactId>cloudevents-http-restful-ws</artifactId>
      <version>${cloudevents.version}</version>
    </dependency>
    <!-- lombok log annotations -->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.22</version>
    </dependency>
  </dependencies>

2. 添加启动类

package com.example.demo;

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

@SpringBootApplication
public class DemoApplication {

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

3. 修改监听端口资源配置

在resource目录下的application.propertiesl文件中配置监听端口号等信息。

server.port=8080

4. 提供接口服务

创建一个MainResource类,提供一个简单的接口服务,用于接收cloudevents事件

package com.example.demo.controller;

import com.example.demo.model.Ks3CloudEventData;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.cloudevents.CloudEvent;
import io.cloudevents.core.builder.CloudEventBuilder;
import io.cloudevents.core.data.PojoCloudEventData;
import io.cloudevents.jackson.PojoCloudEventDataMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;

import static io.cloudevents.core.CloudEventUtils.mapData;

@Path("/")
@Slf4j
public class MainResource {

    @Autowired
    ObjectMapper objectMapper;

    @POST
    @Path("event-invoke")
    public Response fcEventInvoke(CloudEvent inputEvent) throws Exception {
        log.info("receive event message!");
        log.info("event type: {}", inputEvent.getType());
        String ak = (String) inputEvent.getExtension("ak");
        String sk = (String) inputEvent.getExtension("sk");
        //获取extension属性
        log.info("token: " + ak + sk);
        //将data字符数据序列化对象
        PojoCloudEventData<Ks3CloudEventData> cloudEventData = mapData(inputEvent, PojoCloudEventDataMapper.from(objectMapper, Ks3CloudEventData.class));
        if (cloudEventData == null) {
            return Response.status(Response.Status.BAD_REQUEST)
                    .type(MediaType.APPLICATION_JSON)
                    .entity("Event should contain ks3CloudEventData")
                    .build();
        }
       log.info("cloudeventdata: {}", new String(cloudEventData.toBytes()));
       Ks3CloudEventData ks3Data = cloudEventData.getValue();
       log.info("ks3data: {}", ks3Data );
       CloudEvent outputEvent = CloudEventBuilder.from(inputEvent)
           .withData("event invoke".getBytes())
           .withExtension("path", "/event-invoke")
           .build();
        log.info("cloudevent output: {}", outputEvent);
        return Response.ok(outputEvent).build();
    }




    @GET
    @Path("health")
    public Response Health() throws Exception {
        log.info("Health Up");
        return Response.ok("Up").build();
    }
}

其中health路径用于用户程序的健康检查,event-invoke用于事件函数请求响应逻辑,您可以自定义其他的path。

5. 添加JerseyConfiguration类

用于将cloudevents消息进行serializes/deserializes化。

package com.example.demo.controller;

import io.cloudevents.http.restful.ws.CloudEventsProvider;
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JerseyConfiguration extends ResourceConfig {

    public JerseyConfiguration() {
        // Configure Jersey to load the CloudEventsProvider (which serializes/deserializes CloudEvents)
        // and our resource
        registerClasses(CloudEventsProvider.class, MainResource.class);
    }

}

6. Spring Boot 编译打包

在pom.xml文件中添加spring-boot-maven-plugin 插件(打包插件您可以自行选择,此处将spring-boot-maven-plugin插件作为示例)。

 <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${spring-boot.version}</version>
                <configuration>
                    <mainClass>com.example.demo.DemoApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

通过 spring-boot-maven-plugin 构建一个包含所有依赖的 jar 包(FatJar),执行命令:

mvn package

编译后的jar包位于项目文件内的target目录内,可以通过java -jar 【name】运行

7. Gradle编译打包

build.gradle配置文件如下:

plugins {
 id 'org.springframework.boot' version '2.3.2.RELEASE'
 id 'io.spring.dependency-management' version '1.0.11.RELEASE'
 id 'java'
}

group = 'com.example'
version = '1.0-SNAPSHOT'
sourceCompatibility = '1.8'


repositories {
 mavenCentral()
}

dependencies {
 implementation 'org.springframework.boot:spring-boot-starter-jersey'
 compileOnly 'org.projectlombok:lombok'
 annotationProcessor 'org.projectlombok:lombok'
 testImplementation 'org.springframework.boot:spring-boot-starter-test'
 implementation 'io.cloudevents:cloudevents-core:2.3.0'
 implementation 'io.cloudevents:cloudevents-json-jackson:2.3.0'
 implementation 'io.cloudevents:cloudevents-http-restful-ws:2.3.0'
}

tasks.named('test') {
 useJUnitPlatform()
}

在项目的根目录下执行下面命令打包,可将spring boot项目打包成一个包含所有依赖的应用程序

gradle bootJar

编译后的jar包位于项目文件内的build/libs目录下。
如果显示编译失败,请根据输出的编译错误信息调整代码。

文档内容是否对您有帮助?

根本没帮助
文档较差
文档一般
文档不错
文档很好

在文档使用中是否遇到以下问题

内容不全,不深入
内容更新不及时
描述不清晰,比较混乱
系统或功能太复杂,缺乏足够的引导
内容冗长

更多建议

0/200

评价建议不能为空

提交成功!

非常感谢您的反馈,我们会继续努力做到更好!

问题反馈