本文共 3316 字,大约阅读时间需要 11 分钟。
项目工程目录如下
pom.xml(这个服务的命名我就跟网上常有的电商服务类似命名了order-service),相比较服务提供者client-service来说,多增加了一个maven【spring-cloud-starter-feign】 还有使用openFeign包的,具体区别大家自行搜索下。
4.0.0 org.springframework.boot spring-boot-starter-parent 1.5.17.RELEASE com.cloud.order demo 0.0.1-SNAPSHOT orderservice Demo project for Spring Boot 1.8 2021.0.1 org.springframework.cloud spring-cloud-starter-netflix-eureka-client 1.4.6.RELEASE org.springframework.cloud spring-cloud-starter-feign org.springframework.cloud spring-cloud-dependencies Edgware.SR5 pom import org.springframework.boot spring-boot-maven-plugin
启动类OrderserviceApplication(比服务提供者client-service多增加了一个注解@EnableFeignClients)
package com.cloud.order.orderservice;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;import org.springframework.cloud.netflix.feign.EnableFeignClients;@EnableDiscoveryClient@EnableFeignClients@SpringBootApplicationpublic class OrderserviceApplication { public static void main(String[] args) { SpringApplication.run(OrderserviceApplication.class, args); }}
application.properties
server.port=8093spring.application.name=order-serviceeureka.instance.hostname=localhosteureka.client.service-url.defaultZone=http://${eureka.instance.hostname}:8090/eureka
查看工程目录你会发现多增加了一个接口类-FacadeService(这个类名可以随便取啊)
package com.cloud.order.orderservice.business.facade;import org.springframework.cloud.netflix.feign.FeignClient;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestParam;@FeignClient(value = "client-service")public interface FacadeService { @PostMapping("/client/hello/world") String helloWorld(@RequestParam("str") String str);}
DemoController.java
package com.cloud.order.orderservice.business.controller;import com.cloud.order.orderservice.business.facade.FacadeService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/order/hello")public class DemoController { @Autowired private FacadeService facadeService; @PostMapping("/world") public String test() { return facadeService.helloWorld("orderService"); }}
服务启动,访问注册中心,order-service服务在其中已注册。
使用postman直接访问orderService服务的demo接口,可查看到orderService服务通过feign方式调用client-service服务成功。
也使用postman直接访问网关服务zuul通过请求分发到orderService服务,使用调用测试,也可查看到orderService服务通过feign方式调用client-service服务成功。
转载地址:http://tvtdzu.baihongyu.com/