1、Feigin接口: ProductClientService
import com.mengxuegu.springcloud.entities.Product; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import java.util.List; @FeignClient(value = "microservice-product") //指定调用的微服务名称 public interface ProductClientService { @RequestMapping(value = "/product/add", method = RequestMethod.POST) boolean add(@RequestBody Product product); @RequestMapping(value = "/product/get/{id}", method = RequestMethod.GET) Product get(@PathVariable("id") Long id); @RequestMapping(value = "/product/list", method = RequestMethod.GET) Listlist(); }
2、控制器调用feign
ProductController_Feign
import com.mengxuegu.springcloud.entities.Product; import com.mengxuegu.springcloud.service.ProductClientService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController public class ProductController_Feign { @Autowired private ProductClientService productClientService; @RequestMapping(value = "/consumer/product/add") public boolean add(Product product) { return productClientService.add(product); } @RequestMapping(value = "/consumer/product/get/{id}") public Product get(@PathVariable("id") Long id) { return productClientService.get(id); } @RequestMapping(value = "/consumer/product/list") public Listlist() { return productClientService.list(); } }
3、启动类添加注解@EnableFeignClients
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.openfeign.EnableFeignClients; //会扫描指定包下面使用@FeignClient标识的接口 @EnableFeignClients(basePackages = "com.mengxuegu.springcloud.service") @SpringBootApplication @EnableEurekaClient //标识 是一个Eureka客户端 public class ProductConsumer_80_Feign { public static void main(String[] args) { SpringApplication.run(ProductConsumer_80_Feign.class, args); } }
4、pom.xml
com.mengxuegu.springcloud microservice-cloud-02-api ${project.version} org.springframework.boot spring-boot-starter-web org.springframework.cloud spring-cloud-starter-netflix-eureka-client org.springframework.cloud spring-cloud-starter-openfeign
5、验证截图