前言
- 假设我们当前有两个服务:
服务A
,服务B
- 实现效果:
服务B
关联绑定服务A
的API,能够远程调用
以下提供个Demo以供参考
服务A
因为服务A是被调方,故只需有接口就可以了。
package com.xiaobai.feign.controller;
import org.springframework.web.bind.annotation.*;
/**
* @Author xiaobai
* @Date 2023/6/8 15:08
* @Title: HelloController
* @Package com.xiaobai.feign.controller
* @description: 生产者服务 接口
*
*/
@RestController
@RequestMapping("/hello")
public class HelloController {
@GetMapping("/test")
public String testNoParam() {
return "hello feign";
}
@GetMapping("/test/{param}")
public String testParam(@PathVariable String param) {
return "hello feign, say ="+param;
}
}
服务B
启动类添加注解@EnableFeignClients
,以开启 Feign 功能。
package com.xiaobai;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
/**
* @Author xiaobai
* @Date 2023/6/8 15:08
* @Title: BStartApp
* @Package com.xiaobai
* @description: 启动类
*
*/
@EnableFeignClients //加这个注解
@SpringBootApplication
public class BStartApp
{
public static void main( String[] args )
{
SpringApplication.run(BStartApp.class, args);
}
}
绑定远程服务
package com.xiaobai.fegin;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
/**
* @Author xiaobai
* @Date 2023/6/8 15:14
* @Title: HelloFeignService
* @Package com.xiaobai.fegin
* @description: 消费者服务 feign接口实现类
* #########
* 这个类是重点哦!
* 其实这个类相当于就是代理了服务A的接口,所以请求方式、返回值、函数名、所携带的参数等都得统一,并且映射的url路径得写调用接口的全路径。
*/
@FeignClient(name = "service-a") //被调服务名
public interface HelloFeignService {
@GetMapping("/service-a/hello/test")
String testNoParam();
/**
* 映射的url,这里路径得写调用接口的全路径
* @return
*/
@GetMapping("/service-a/hello/test/{param}")
String testParam(@PathVariable String param);
}
消费者接口
package com.xiaobai.fegin.controller;
import com.xiaobai.fegin.HelloFeignService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
/**
* @Author xiaobai
* @Date 2023/6/8 15:11
* @Title: HelloFeignController
* @Package com.xiaobai.fegin.controller
* @description: 消费者服务 接口
*/
@RestController
@RequestMapping("/hello")
public class HelloFeignController {
@Resource
private HelloFeignService helloFeignService;
@GetMapping("/test")
public String testNoParam() {
return helloFeignService.testNoParam();
}
@GetMapping("/test/{param}")
public String testParam(@PathVariable String param) {
return helloFeignService.testParam(param);
}
}
效果