微服务服务消费。一般使用feign和rebion来调用服务进行服务消费。本文将通过实战代码来讲解服务消费。微服务环境搭建创建springboot项目,springboot是拆分服务的最小服务单元。添加maven依赖基础的maven依赖org.springframework.bootspring-boot-starter-weborg.springframework.云spring-cloud-starter-alibaba-nacos-discoveryorg.springframework.bootspring-boot-starter-testtestrebion依赖org.springframework.cloudspring-cloud-starter-netflix-ribbonfeign依赖org.springfframework.cloudspring-cloud-starter-openfeignfeign依赖包括rebion依赖。如果想同时使用feign和rebion依赖,只需要参考feign添加application.ymlspring:cloud:nacos:discovery:server-addr:127.0.0.1:8848添加Appcation.java启动类@SpringBootApplication//Registerservicetoregistry@EnableDiscoveryClient//扫描并注册feign客户端bean定义@EnableFeignClientspublicclassNacosConsumeApplication{publicstaticvoidmain(String[]args){SpringApplication.run(NacosConsumeApplication.class,args);其中@EnableDiscoveryClient将服务注册到注册表,@EnableFeignClients扫描并注册假客户端bean定义。feginbean定义是@FeignClient。服务调用:feign和ribbon1。feign创建feignclient@FeignClient(value="service-provider")publicinterfaceProductClient{@GetMapping("/hello")Stringproduct(@RequestParam("name")Stringname);}这里@FeignClient是创建一个bean扫描@EnableFeignClients注册。@FeignClient中的配置值对应服务提供者的服务名称,@GetMapping中的值对应服务提供者的@GetMapping路径。这样做的好处是这里直接配置路径和服务名,不需要调用者做任何配置。创建请求调用feignclient@RestControllerpublicclassFeignController{//这个错误是编译器的问题。因为这个bean是在程序启动的时候注入的,编译器无法感知,所以报错。@AutowiredprivateProductClientproductClient;@GetMapping("/feign")publicStringfeign(Stringname){returnproductClient.product(name);}}2。rebion配置RestTemplatebean@ConfigurationpublicclassRibbonConfig{@LoadBalanced@BeanpublicRestTemplaterestTemplate(){returnnewRestTemplate();}}呼叫服务@RestControllerpublicclassRibbonController{@AutowiredprivateRestTemplaterestTemplate;@GetMapping("/ribbon")publicStringribbon(Stringname){Stringresult=restTemplate.getForObject("http://service-provider/hello?name="+name,String.class);返回结果;}}feign和rebion的优缺点feign的配置比较简单明了。配置好FeignClient后可以直接调用,但是后续配置有冗余。Rebion每次都需要配置请求路径。它的优点是可以直接调用,不需要单独配置客户端。