✨✨个人主页:沫洺的主页
📚📚系列专栏: 📖 JavaWeb专栏📖 JavaSE专栏 📖 Java基础专栏📖vue3专栏
📖MyBatis专栏📖Spring专栏📖SpringMVC专栏📖SpringBoot专栏
📖Docker专栏📖Reids专栏📖MQ专栏📖SpringCloud专栏
💖💖如果文章对你有所帮助请留下三连✨✨
创建子模块user-api
pom.xml引入最小的依赖
"1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0modelVersion> <parent> <groupId>com.mominggroupId> <artifactId>spring-cloud-rootartifactId> <version>0.0.1-SNAPSHOTversion> <relativePath>../pom.xmlrelativePath> parent> <artifactId>user-apiartifactId> <dependencies> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-webartifactId> dependency> dependencies> project>父类pom中指定模块
<module>user-apimodule>
整理模块结构,改删的删
定义接口
public interface IUserService { //通过用户Id返回用户名称 /user/name?id=12 @GetMapping("/user/name") String getName(@RequestParam Integer id); //通过用户Id返回用户金额 /user/amount?id=12 @GetMapping("/user/amount") Integer getAmount(@RequestParam Integer id); }接下来模拟个场景,子模块a要去调用api中的接口
a模块导入api依赖坐标
<dependency> <groupId>com.mominggroupId> <artifactId>user-apiartifactId> <version>0.0.1-SNAPSHOTversion> <scope>compilescope> dependency>创建实现类去实现IUserService,模拟返回指定数据
@RestController public class UserServiceImpl implements IUserService { @Override public String getName(Integer id) { return "张"+id; } @Override public Integer getAmount(Integer id) { return id*100; } }启动a模块,测试接口
然后b模块去调用a服务时,就可以在AServiceClient中去实现IUserService
@FeignClient("a") public interface AServiceClient extends IUserService { //@GetMapping("/a/test") //String test(@RequestParam(value = "name",required = false) String name); // //@GetMapping("/a/age/{age}") //String age(@PathVariable Integer age); }Debug测试
@RestController public class B { @Autowired private AServiceClient aServiceClient; @GetMapping("use-openfeign") public String callAServer(@RequestParam(value = "nickName",required = false) String nickName){ //String value = aServiceClient.test(nickName); //String value2 = aServiceClient.age(18); String value = aServiceClient.getName(3); return value; } //@Autowired //private RestTemplate restTemplate; //@GetMapping("/b/test") //public String test(@RequestParam(value = "nickName",required = false) String nickName){ // //希望访问到A的应用 // String ret = restTemplate.getForObject("http://a/a/test?name=张三", String.class); // return ret+"的小名: "+nickName; //} }