听着题目是不是感觉很高大上?但是感觉其实实际项目中使用有点鸡肋,只是公司项目中突然大规模使用这个东西了,那今天就说说吧~
1、首先构建一个简单的Spring boot web 工程,此处省略。
2、加入项目依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
注意,此处可能会有加入依赖后项目启动不了,注意调整 依赖的版本。
3、实现代码,此处以一个公共免费的证件号码的解析为远程服务例子。
启动类加入注解
@SpringBootApplication
@EnableFeignClients
public class SpringbootFeignClientApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootFeignClientApplication.class, args);
}
}
服务类接口 CardService.class
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient(name = "card-service", url = "http://api.guaqb.cn")
public interface CardService {
/**
* 解析接口
*
* @param id
* @return
*/
@RequestMapping(value = "/music/id/card.php", method = RequestMethod.GET)
String resolve(@RequestParam(value = "id") String id);
}
调用类:UserController.class
@RestController
public class UserController {
@Autowired
private CardService cardService;
@RequestMapping("/test")
public void remoteApi() {
String id = "110101199003077395";
String msg = cardService.resolve(id);
System.out.println(msg);
}
}
发起请求:
curl localhost:9002/test
打印结果:
{"msg":"ok","region":"北京市东城区","birthday":"1990-03-07","gender":"男","age":29,"adult":"成年人","zodiac":"马","constellation":"双鱼座"}
项目上传地址:
https://github.com/shihongwei/springboot-feign-client
其实实现思路也很简单就是生成一个代理类,请求地址 参数指向远程服务接口。