如何使用Spring Cloud构建微服务架构?
|
@EnableDiscoveryClient @SpringBootApplication public class ConsumerApplication { @Bean @LoadBalanced RestTemplate restTemplate() { return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(ConsumerApplication.class, args) } } 假设消费 demo-service 的客户端代码写在 demo-consumer 服务的其中一个 Controller 中: @RestController public class ConsumerController { @Autowired RestTemplate restTemplate; @RequestMapping(value = "/demo-consumer", method = RequestMethod.Get) public String helloConsumer() { return restTemplate.getForEntity("http://demo-service/demo", String.class).getBody(); } } 通过 RestTemplate 就可以发起对 demo-service 的消费调用。 声明式服务调用 通过 Ribbon 和 Hystrix 可以实现对微服务的调用以及容错保护,但 Spring Cloud 还提供了另一种更简单的声明式服务调用方式,即 Spring Cloud Feign。 Feign 实际上就是对 Ribbon 与 Hystrix 的进一步封装。通过 Feign,我们只需创建一个接口并用 annotation 的方式配置,就可以完成对服务供应方的接口(REST API)绑定。 假设我们有三个服务: Notification Service Account Service Statistics Service 服务之间的依赖关系如下图所示: 要使用 Feign 来完成声明式的服务调用,需要在作为调用者的服务中创建 Client。 Client 通过 Eureka Server 调用注册的对应服务,这样可以解除服务之间的耦合。 结构如下图所示: 为了使用 Feign,需要对应微服务的 pom.xml 文件中添加如下依赖: <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> </dependency> 同时,还需要在被消费的微服务 Application 中添加 @EnableFeignClients 注解。 例如在 Statistics 服务的应用程序类中: @SpringBootApplication @EnableDiscoveryClient @EnableFeignClients public class StatisticsApplication { public static void main(String[] args) { SpringApplication.run(StatisticsApplication.class, args); } } 由于 Account 服务需要调用 Statistics 服务,因此需要在 Account 服务项目中增加对应的 Client 接口: @FeignClient(name = "statistics-service") public interface StatisticsServiceClient { @RequestMapping(method = RequestMethod.PUT, value = "/statistics/{accountName}", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) void updateStatistics(@PathVariable("accountName") String accountName, Account account); } StatisticsServiceClient 接口的 updateStatistics() 方法会调用 URI 为 /statistics/{accountName} 的 REST 服务,且 HTTP 动词为 put。 这个服务对应的就是 Statistics Service 中 StatisticsController 类中的 saveStatistics() 方法: (编辑:PHP编程网 - 湛江站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |




