Using OpenFeign to realize remote calls in microservices

premise

import dependencies

<!-- Open Feign,他里面也有ribbon,所以有负载均衡 -->
 <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

Join the registry (both the caller and the callee need to join the registry)

# 我这里注册中心中的nacos
spring:
 datasource:
   username: root
   password: root
   url: jdbc:mysql://xxx.xxx.x.xx:3306/gulimall_sms?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai
 application:
   name: gulimall-coupon
 cloud:
   nacos:
     discovery:
       server-addr: 192.168.2.88:8848

1. The called microservice

1. Enable service registration and discovery

@EnableDiscoveryClient//开启注册中心,注册与发现
@SpringBootApplication
public class GulimallCouponApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(GulimallCouponApplication.class, args);
    }
}

2. The interface that needs to be called

@RestController
public class Test {
    
    
    @GetMapping("/coupon/test1")
    public String test(){
    
    
        return "test success!";
    }
}

Second, the caller

1. Enable service registration and discovery and enable remote call function

//com.atguigu.gulimall.product.feign是我们专门写远程调用方法的包
@EnableFeignClients("com.atguigu.gulimall.product.feign")//开启远程调用
@EnableDiscoveryClient//开启注册发现
@SpringBootApplication
public class GulimallProductApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(GulimallProductApplication.class, args);
    }

}

2. Remote call

First create an interface

  • The interface needs to add registration @FeignClient("xxxx") to indicate which microservice we need to call
  • Create a method corresponding to what we need to call the remote interface
  • Write the mapping address on the method, which needs to correspond to the remote interface path we call
@FeignClient(value = "gulimall-coupon")
public interface CouponFeignService {
    
    
    @GetMapping("/coupon/test1")//这里的请求地址需要和被调用的地址一样
    String test();
}

3. Test

@RestController
public class Test {
    
    
    @Autowired
    CouponFeignService couponFeignService;
    //测试优惠服务的远程调用
    @GetMapping("/test/test/1")
    public String test(){
    
    
        return couponFeignService.test();
    }
}

おすすめ

転載: blog.csdn.net/weixin_44485316/article/details/131617479