Apache Camel,Spring Boot 创建web服务,接收http请求,并进行响应

基本框架

  • Apache Camel

  • Spring Boot

  • Maven

开发过程

1.新建一个POM(quickstart)项目,在POM文件中添加Camel,Spring Boot,jetty的依赖


  org.springframework.boot
  spring-boot-starter-parent
  1.4.1.RELEASE


 
 org.apache.camel 
 camel-spring-boot-starter 
 2.18.1


  org.apache.camel
  camel-jetty
  


2.新建Application.java 启动类

@SpringBootApplication
public class Application{
    public static void main(String[] args) {
          final ApplicationContext context = new SpringApplication(Application.class).run(args);
          final CamelSpringBootApplicationController controller = context.getBean(CamelSpringBootApplicationController.class);
          controller.run();
    }
}

3.新建一个HttpRouteBuilder.java

@Component
public class HttpRouteBuilder extends SpringRouteBuilder{
    @Override
    public void configure() throws Exception {
        from("jetty:http://localhost:8080/myapp/myservice").process(new MyBookProcessor());
    }  
}

4.新建MyBookProcessor.java

@Component
public clas MyBookProcessor implements Processor {
    @Override
    public void process(Exchange exchange) throws Exception{
         exchange.getOut().setBody("Book is good");
    }
}

5.使用浏览器访问http://localhost:8080/myapp/myservice
浏览器显示 Book is good

6.获取http请求的参数
比如http请求为:http://localhost:8080/myapp/myservice?bookId=1&categoryId=2,从exchange.getIn().getHeader("xxx")就可以获取到相应的参数值
修改MyBookProcessor.java

private static final Logger LOGGER = LoggerFactory.getLogger(MyBookProcessor.class);
public clas MyBookProcessor implements Processor {
    @Override
    public void process(Exchange exchange) throws Exception{
        LOGGER.info("bookId={},categoryId={}", exchange.getIn.getHeader("bookId"), exchange.getIn().getHeader("categoryId"));
        exchange.getOut().setBody("Book is good");
    }
}

7.使用jetty作为web服务时,endpoint的格式
jetty:http://{ip_address}:{port}/{path}
如果ip_address 指定为0.0.0.0,就可以监听全网

8.连接DB,响应合适的结果
在获取到http请求的参数之后,可以通过spring-jpa或者其他ORM连接DB,查询到需要的数据,进行响应

你可能感兴趣的:(Apache Camel,Spring Boot 创建web服务,接收http请求,并进行响应)