How to use open-feign to call microservices in SpringCloud distributed (provided that the services must be registered to the registry [zookeeper, or nocas])

1. Introduce open-feign

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

2. Write an interface and tell SpringCloud that this interface needs to call remote services

  • The interface is written in this service.
  • @FeignClient(value = ""), valueThe name of the remote service to be called.
  • @RequestMapping(value = ""), valueThe method request path of the remote service.
  • The meaning of this interface is what service and method to call.
  • Declare that each method of the interface is the request to call which remote service
@FeignClient(value = "application.name")
public interface CouponFeignService {
    
    
    @RequestMapping("请求路径")
    // 该名字可以与远程服务不一样
    public R coupons();
}

3. Open remote service call

  • @EnableFeignClientsOpen the remote service call, basePackagesdeclare the package where the interface is located (you don’t need to write it)
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients(basePackages = "")
public class MemberApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(MemberApplication.class, args);
    }

}

4. There are two ways to request remote data (provided that the gateway is configured)

  • Let all requests be sent to the gateway, and then forwarded by the gateway to the corresponding service
  • Send directly to the service as above

5. The process of remotely invoking the service

     * 1 FeignService.saveXXX(XXXTo)
     *      1 SpringCloud 会将这个对象转为json
     *      2 找到对应的微服务,给相应请求/xx/xxx发送请求
     *      将上一步转的jso放在请求位置,发送请求
     *      3 对方服务受到请求,请求体里面有json数据,
     *      @RequestBody XXXEntity xxx 将请求体的json转为XXXEntity
     * 只要json数据模型是兼容的,双方服务无需使用同一个to

Guess you like

Origin blog.csdn.net/JISOOLUO/article/details/105577790