加入收藏 | 设为首页 | 会员中心 | 我要投稿 PHP编程网 - 湛江站长网 (https://www.0759zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 教程 > 正文

如何使用Spring Cloud构建微服务架构?

发布时间:2018-08-20 04:28:42 所属栏目:教程 来源:张逸
导读:副标题#e# 【资讯】微服务架构模式的核心在于如何识别服务的边界,设计出合理的微服务。 但如果要将微服务架构运用到生产项目上,并且能够发挥该架构模式的重要作用,则需要微服务框架的支持。 在 Java 生态圈,目前使用较多的微服务框架就是集成了包括 Net

  @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

  服务之间的依赖关系如下图所示:

  如何使用Spring Cloud构建微服务架构?

  要使用 Feign 来完成声明式的服务调用,需要在作为调用者的服务中创建 Client。

  Client 通过 Eureka Server 调用注册的对应服务,这样可以解除服务之间的耦合。

  结构如下图所示:

  如何使用Spring Cloud构建微服务架构?

  为了使用 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编程网 - 湛江站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!