Vertx与Spring配合完成DML操作

心不动则不痛 提交于 2019-11-27 02:51:33

服务启动:

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

 EventBus接受给Service:

 1 public class SpringSimpleVerticle extends AbstractVerticle {
 2  
 3     public static final String ALL_PRODUCTS_ADDRESS = "example.all.products";
 4  
 5  
 6     private final ObjectMapper mapper = new ObjectMapper();
 7     private final ProductService service;
 8  
 9     public SpringSimpleVerticle(final ApplicationContext context) {
10  
11         service = (ProductService) context.getBean("productService");
12  
13     }
14  
15     private Handler<Message<String>> allProductsHandler(ProductService service, String name) {
16         return ms2g -> vertx.<String>executeBlocking(future -> {
17                     try {
18                         future.complete(mapper.writeValueAsString(service.getAllProducts(ms2g.body())));
19                     } catch (JsonProcessingException e) {
20                         System.out.println("Failed to serialize result");
21                         future.fail(e);
22                     }
23                 },
24                 result -> {
25                     if (result.succeeded()) {
26                         ms2g.reply(result.result());
27                     } else {
28                         ms2g.reply(result.cause().toString());
29                     }
30                 });
31     }
32  
33     @Override
34     public void start() throws Exception {
35         super.start();
36  
37         System.out.println("<<<<<<<<<<<<<<<<<<<<<<< CONSUMER >>>>>>>>>>>>>>>>>>>>>>>>>");
38         vertx.eventBus().<String>consumer(ALL_PRODUCTS_ADDRESS).handler(allProductsHandler(service, "message"));
39  
40     }
41 }

端口监听:

 1 @Service
 2 public class ProductService {
 3  
 4     @Autowired
 5     private ProductRepository repo;
 6  
 7     public List<Product> getAllProducts(String productId) {
 8         System.out.println("productid : " + productId);
 9         return repo.findAll();
10     }
11  
12     public void getProduct(String productId) {
13         System.out.println("productid : " + productId);
14     }
15  
16 }

 

结论:

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!