gpt4 book ai didi

java - 使用 Camel 和 Spring-boot 构建 REST 应用程序

转载 作者:行者123 更新时间:2023-11-29 08:44:09 25 4
gpt4 key购买 nike

基本上,我希望能够在 JSON 中发布一个对象并使用 Java 打印该对象的详细信息。

为了实现我想要(而且我必须)使用 SPRING-BOOT 和 Camel

这是代表我的对象的类:

    public class Response {
private long id;
private String content;

public Response(){

}

public Response(long id, String content) {
this.id = id;
this.content = content;
}

public long getId() {
return id;
}

public void setId(long id) {
this.id = id;
}

public String getContent() {
return content;
}

public void setContent(String content){
this.content = content;
}

}

然后我有一个 Rest Controller :

    @RestController
public class BasicController {

private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();

//Handle a get request
@RequestMapping("/test")
public Response getResponse(@RequestParam(value="name", defaultValue="World") String name) {
System.out.println("Handle by spring");
return new Response(counter.incrementAndGet(),
String.format(template, name));
}

//Handle a post request
@RequestMapping(value = "/post", method = RequestMethod.POST)
public ResponseEntity<Response> update(@RequestBody Response rep) {

if (rep != null) {
rep.setContent("HANDLE BY SPRING");
}
return new ResponseEntity<Response>(rep, HttpStatus.OK);
}
}

使用此代码我可以处理发布请求和打印详细信息,但我必须使用 Camel。所以我尝试了以下操作:

1)我添加了一个bean conf

@SpringBootApplication
public class App
{

private static final String CAMEL_URL_MAPPING = "/camel/*";
private static final String CAMEL_SERVLET_NAME = "CamelServlet";

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

@Bean
public ServletRegistrationBean servletRegistrationBean() {
ServletRegistrationBean registration = new ServletRegistrationBean(new CamelHttpTransportServlet(), CAMEL_URL_MAPPING);
registration.setName(CAMEL_SERVLET_NAME);
return registration;
}
}

2) 然后我创建了 2 条路线。

<?xml version="1.0" encoding="UTF-8"?>
<routes xmlns="http://camel.apache.org/schema/spring">
<!-- <route id="test"> -->
<!-- <from uri="timer://trigger"/> -->
<!-- <to uri="log:out"/> -->
<!-- </route> -->
<route id="test2">
<from uri="servlet:///test"/>
<to uri="log:Handle by camel"/>
</route>
</routes>

有了这个,我就可以在 Camel 上递交请求了。但我不知道如何在 Spring 和 Camel 之间建立联系。有没有办法用我的 Spring Controller 处理请求然后调用 Camel 路线?在同一个 URL 上..

最佳答案

您可以使用 Autowiring 的 producerTemplate 来调用 Camel 路由。如果您添加依赖项,它将被创建:

<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-spring-boot</artifactId>
<version>${camel.version}</version> <!-- use the same version as your Camel core version -->
</dependency>

有关更多信息,您可以查看 Camel 文档 here .

在你的情况下,你会调用类似的东西:

producerTemplate.sendBody...

关于java - 使用 Camel 和 Spring-boot 构建 REST 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37701798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com