Vertx与Spring配合完成DML操作

42 篇文章 0 订阅
38 篇文章 0 订阅

前言

vertx相较于Tomcat不同之处

引用oschina上关于vertx的文章,感觉他说得非常明白,不在这里过多讨论,这里我简单说明下如何在vertx和spring配合完成基础任务。

 

服务启动:

  public static void main( String[] args ) {
    ApplicationContext context = new AnnotationConfigApplicationContext(SimpleSpringConfiguration.class);
    final Vertx vertx = Vertx.vertx();
    vertx.deployVerticle(new SpringSimpleVerticle(context));
    vertx.deployVerticle(new ServerVerticle());
  }

 

 EventBus接受给Service:

public class SpringSimpleVerticle extends AbstractVerticle {

    public static final String ALL_PRODUCTS_ADDRESS = "example.all.products";


    private final ObjectMapper mapper = new ObjectMapper();
    private final ProductService service;

    public SpringSimpleVerticle(final ApplicationContext context) {

        service = (ProductService) context.getBean("productService");

    }

    private Handler<Message<String>> allProductsHandler(ProductService service, String name) {
        return ms2g -> vertx.<String>executeBlocking(future -> {
                    try {
                        future.complete(mapper.writeValueAsString(service.getAllProducts(ms2g.body())));
                    } catch (JsonProcessingException e) {
                        System.out.println("Failed to serialize result");
                        future.fail(e);
                    }
                },
                result -> {
                    if (result.succeeded()) {
                        ms2g.reply(result.result());
                    } else {
                        ms2g.reply(result.cause().toString());
                    }
                });
    }

    @Override
    public void start() throws Exception {
        super.start();

        System.out.println("<<<<<<<<<<<<<<<<<<<<<<< CONSUMER >>>>>>>>>>>>>>>>>>>>>>>>>");
        vertx.eventBus().<String>consumer(ALL_PRODUCTS_ADDRESS).handler(allProductsHandler(service, "message"));

    }
}

 传统Service+Dao

@Service
public class ProductService {

    @Autowired
    private ProductRepository repo;

    public List<Product> getAllProducts(String productId) {
        System.out.println("productid : " + productId);
        return repo.findAll();
    }

    public void getProduct(String productId) {
        System.out.println("productid : " + productId);
    }

}

 

端口监听:

public class ServerVerticle extends AbstractVerticle {

  @Override
  public void start() throws Exception {
    super.start();
    HttpServer server = vertx.createHttpServer();
    server.requestHandler(req -> {
      if (req.method() == HttpMethod.GET) {
        req.response().setChunked(true);

        if (req.path().equals("/products")) {
          vertx.eventBus().<String>send(SpringSimpleVerticle.ALL_PRODUCTS_ADDRESS, "123456", result -> {
            if (result.succeeded()) {
              req.response().setStatusCode(200).write(result.result().body()).end();
            } else {
              req.response().setStatusCode(500).write(result.cause().toString()).end();
            }
          });
        } else {
          req.response().setStatusCode(200).write("Hello from vert.x").end();
        }

      } else {
        // We only support GET for now
        req.response().setStatusCode(405).end();
      }
    });

    server.listen(8080);
  }
}

 

结论:

DML操作基本都是类似的做法,但是观念的改变其实很大,传统烟囱的方式=》基于消息、事件的方式转移

要在Spring Boot中整合Vert.x开发MQTT应用程序,可以按照以下步骤进行操作: 1. 添加依赖:在项目的pom.xml文件中添加以下依赖,包括Vert.x和MQTT相关的依赖: ```xml <dependency> <groupId>io.vertx</groupId> <artifactId>vertx-spring-boot-starter</artifactId> <version>2.1.6</version> </dependency> <dependency> <groupId>io.vertx</groupId> <artifactId>vertx-mqtt-server</artifactId> <version>4.2.1</version> </dependency> ``` 2. 创建MQTT服务器:在Spring Boot应用程序的入口类中,创建一个Vert.x的`Vertx`实例,并使用`Vertx`实例创建一个`MqttServer`实例。 ```java import io.vertx.core.Vertx; import io.vertx.mqtt.MqttServer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } @Bean public MqttServer mqttServer(Vertx vertx) { return MqttServer.create(vertx); } } ``` 3. 编写MQTT消息处理器:创建一个实现`MqttEndpointHandler`接口的类,用于处理接收到的MQTT消息。可以根据业务需求自定义消息处理逻辑。 ```java import io.vertx.mqtt.MqttEndpoint; import io.vertx.mqtt.MqttEndpointHandler; public class MyMqttEndpointHandler implements MqttEndpointHandler { @Override public void handle(MqttEndpoint endpoint) { // 处理消息逻辑 } } ``` 4. 注册MQTT消息处理器:在Spring Boot应用程序的入口类中,将自定义的`MqttEndpointHandler`实例注册到`MqttServer`中。 ```java import io.vertx.core.Vertx; import io.vertx.mqtt.MqttServer; import io.vertx.mqtt.MqttServerOptions; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } @Bean public MqttServer mqttServer(Vertx vertx, MqttEndpointHandler endpointHandler) { MqttServerOptions options = new MqttServerOptions() .setPort(1883); // 设置MQTT服务器端口 MqttServer mqttServer = MqttServer.create(vertx, options); mqttServer.endpointHandler(endpointHandler); // 注册消息处理器 return mqttServer; } @Bean public MqttEndpointHandler endpointHandler() { return new MyMqttEndpointHandler(); } } ``` 通过以上步骤,你就可以在Spring Boot应用程序中使用Vert.x开发MQTT应用程序了。启动应用程序后,Vert.x MQTT服务器将在指定的端口上监听并处理接收到的MQTT消息。你可以根据需要在`MyMqttEndpointHandler`中编写自定义的消息处理逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值