SpringCloud ------ Feign use

1. Official documents

https://cloud.spring.io/spring-cloud-static/spring-cloud-openfeign/2.2.2.RELEASE/reference/html/

 

2. Add dependence

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

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

 

3. Add the startup class notes

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
//@MapperScan("cn.ytheng.order_service")
@EnableFeignClients
public class OrderServiceApplication {

    public static void main(String[] args) {

        SpringApplication.run(OrderServiceApplication.class, args);
    }

}

 

4. Add Feign Interface

Import org.springframework.cloud.openfeign.FeignClient;
 Import org.springframework.web.bind.annotation.GetMapping;
 Import org.springframework.web.bind.annotation.RequestParam; 

/ ** 
 * 
 * Goods Services client 
 * product-service : call service name, that spring.application.name 
 * 
 * / 
@FeignClient (name = "Product-service" )
 public  interface ProductClient { 

    @GetMapping ( "/ API / v1 / Product / the Find" ) 
    String getById (@RequestParam ( " ID ") int ID); 

}

 

5. Add Controller

import cn.theng.order_service.service.ProductClient;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1/order")
public class ProductOrderController {

    @Autowired
    private ProductClient productClient;

    @PostMapping("/test2")
    public Object test2(@RequestParam("product_id") int productId) {

        String product = productClient.getById(productId);

        return "success";
    }
}

 

6. Add application.yml configuration

server:
  port: 8781
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

spring:
  application:
    name: order-service

 

7. Visit Location

 

Guess you like

Origin www.cnblogs.com/tianhengblogs/p/12483984.html