✨✨个人主页:沫洺的主页
📚📚系列专栏: 📖 JavaWeb专栏📖 JavaSE专栏 📖 Java基础专栏📖vue3专栏
📖MyBatis专栏📖Spring专栏📖SpringMVC专栏📖SpringBoot专栏
📖Docker专栏📖Reids专栏📖MQ专栏📖SpringCloud专栏
💖💖如果文章对你有所帮助请留下三连✨✨
衔接上篇
注意创建的子模块要在父模块的pom.xml中声明一下
子模块spring-cloud-eureka-a
pom文件如下
4.0.0 com.moming spring-cloud-root 0.0.1-SNAPSHOT ../pom.xml spring-cloud-eureka-a org.springframework.boot spring-boot-starter-web org.springframework.cloud spring-cloud-starter-netflix-eureka-client org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin application.properties建立a应用
server.port = 9091 spring.application.name = a eureka.client.service-url.defaultZone=http://ek1.cn:8001/eureka/,http://ek2.cn:8002/eureka/
创建测试接口controller/A
@RestController public class A {@GetMapping("/a/test")public String test(@RequestParam(value = "name",required = false) String name){return "这是A应用返回的接口,参数为: "+name;} }
启动项目,即可查看服务注册成功
访问a应用
子模块spring-cloud-eureka-b
创建同理
pom.xml
4.0.0 com.moming spring-cloud-root 0.0.1-SNAPSHOT ../pom.xml spring-cloud-eureka-b org.springframework.boot spring-boot-starter-web org.springframework.cloud spring-cloud-starter-netflix-eureka-client org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin application.properties建立b应用
server.port = 9092 spring.application.name = b #注册中心 eureka.client.service-url.defaultZone=http://ek1.cn:8001/eureka/,http://ek2.cn:8002/eureka/
启动类添加@EnableDiscoveryClient注解
@SpringBootApplication //能从服务中心拉东西 @EnableDiscoveryClient public class App {public static void main(String[] args) {SpringApplication.run(App.class, args);} }
注册RestTemplate,代码如下
@Configuration public class RestTemplateConfig {@Bean@LoadBalanced//负载均衡功能public RestTemplate restTemplate(){return new RestTemplate();} }
创建测试接口controller/B.调用a服务对应接口
@RestController public class B {@Autowiredprivate 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;} }
同时运行A,B服务
访问b应用,调用a服务对应接口成功