springCloud学习笔记2(服务发现) (3)

  这种方法是较为常用的微服务通信机制之一。要启动该功能,需要使用 Spring Cloud 注解@LoadBanced 来定义 RestTemplate bean 的构造方法。方便起见直接在启动类中定义 bean:

#LicensingserviceApplication.java @SpringBootApplication @EnableDiscoveryClient //使用不带Ribbon功能的Spring RestTemplate,其他情况下可删除 public class LicensingserviceApplication { /** * 使用带有Ribbon 功能的Spring RestTemplate,其他情况可删除 */ @LoadBalanced @Bean public RestTemplate getRestTemplate(){ return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(LicensingserviceApplication.class, args); } }

  接着 service 包下增加一个类:OrganizationByRibbonService.java

@Component public class OrganizationByRibbonService { private RestTemplate restTemplate; @Autowired public OrganizationByRibbonService(RestTemplate restTemplate) { this.restTemplate = restTemplate; } public Organization getOrganizationWithRibbon(String id) { ResponseEntity<Organization> responseEntity = restTemplate.exchange("http://organizationservice/organization/{id}", HttpMethod.GET, null, Organization.class, id); return responseEntity.getBody(); } }

  最后就是在 LicensingController.js 中加一个访问路径:

//不要忘记注入OrganizationByRibbonService服务 @GetMapping("/licensingByRibbon/{orgId}") public Licensing getLicensingByRibbon(@PathVariable("orgId") String orgId) { Licensing licensing = new Licensing(); licensing.setValid(false); licensing.setOrganization(organizationService.getOrganization(orgId)); return licensing; } }

  访问localhost:10011/licensingByRibbon/113,即可看到结果。

c、使用 Netflix Feign 客户端调用

  Feign 客户端是 Spring 启用 Ribbon 的 RestTemplate 类的替代方案。开发人员只需定义一个接口,然后使用 Spring 注解来标注接口,即可调用目标服务。除了编写接口定义无需编写其他辅助代码。

  首先启动类上加一个@EnableFeignClients注解启用 feign 客户端。然后在 POM 中加入 Feign 的依赖

<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> </dependency>

  然后在 client 包下新建 OrganizationFeignClient.java

@FeignClient("organizationservice")//使用FeignClient注解指定目标服务 public interface OrganizationFeignClient { /** * 获取组织信息 * * @param orgId 组织id * @return Organization */ @RequestMapping(method = RequestMethod.GET, value = "/organization/{orgId}", consumes = "application/json") Organization getOrganization(@PathVariable("orgId") String orgId); }

  最后修改LicensingController.java,加入一个路由调用 Feign。

//注入OrganizationFeignClient,使用构造注入 @GetMapping("/licensingByFeign/{orgId}") public Licensing getLicensingByFeign(@PathVariable("orgId") String orgId) { Licensing licensing = new Licensing(); licensing.setValid(false); licensing.setOrganization(organizationFeignClient.getOrganization(orgId)); return licensing; }

访问localhost:10011/licensingByFeign/11313,即可看到结果。

总结

  这一节磨磨蹭蹭写了好几天,虽然例子很简单,但是相信应该是能够看懂的。由于篇幅原因代码没有全部贴上,想要查看完整代码,可以访问这个链接:点击跳转。

本篇原创发布于:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpjwws.html