spring微服务实战 - 1 一个完整的HTTP JSON REST服务

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PathVariable;

@SpringBootApplication
@RestController
@RequestMapping(value="hello")
public class Application {

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

    @RequestMapping(value="/{firstName}/{lastName}",method = RequestMethod.GET)
    public String hello( @PathVariable("firstName") String firstName,
                         @PathVariable("lastName") String lastName) {

        return String.format("{\"message\":\"Hello %s %s\"}", firstName, lastName);
    }
}

@SpringBootApplication告诉Spring Boot框架,该类是Spring Boot服务的入口

@RestController告诉Spring Boot,要将该类中的代码公开为Spring RestController类

@RequestMapping(value="hello")此应用程序中公开的所有URL将以/hello前缀开头

@PathVariable("firstName")将URL中传入的firstname参数映射为传递给hello方法的变量

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

访问http://localhost:8080/hello/tang/xin,返回{"message":"Hello tang xin"}

一些注解的解释*

@EnableCircuitBreaker告诉Spring微服务,将要在应用程序使用Netflix Hystrix库。

@EnableEurekaClient告诉微服务使用Eureka服务发现代理去注册它自己,并且将要在代码中使用服务发现去查询远程REST服务端点。

@HystrixCommand做两件事:

  1. 在任何时候调用helloRemoteServiceCall方法,该方法都不会被直接调用,这个调用会被委派给由Hystrix管理的线程池。如果调用时间太长(默认为1s),Hystrix将介入并中断调用。这是断路器模式的实现。
  2. 创建一个由Hystrix管理的名为helloThreadPool的线程池。所有对helloRemoteServiceCall方法的调用只会发生在此线程池中,并且将与正在进行的任何其他远程服务调用隔离。
posted @ 2020-01-06 15:30  白芷呀  阅读(569)  评论(0编辑  收藏  举报