本文主要是介绍Springcloud微服务注册中心-Eureka 2.X(二)——服务消费者调用服务提供者,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.Eureka服务注册中心运行原理
2.创建服务提供者,服务消费者
- 创建基本的Eureka-client工程,
app-eureka-clientOrder是服务消费者 app-eureka-clientMember是服务提供者 Springcloud-Eureka是服务注册中心
- 服务提供者app-eureka-clientMember(服务别名)启动服务:
package com.eureka.eurekaclient;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;@SpringBootApplication
@EnableEurekaClient
public class EurekaClientApplication {public static void main(String[] args) {SpringApplication.run(EurekaClientApplication.class, args);}}
- 服务提供者app-eureka-clientMember(服务别名)服务接口:
package com.eureka.eurekaclient.Member;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class MemberController {@RequestMapping("/getMember")public String getMember() {return "this is getMember";}
}
- 服务消费者app-eureka-clientOrder(服务别名)启动消费者服务:
package com.eureka.eurekaclient;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;@SpringBootApplication
@EnableEurekaClient
public class EurekaClientApplication {public static void main(String[] args) {SpringApplication.run(EurekaClientApplication.class, args);}@Bean@LoadBalancedRestTemplate restTemplate() {return new RestTemplate();}}
- 服务消费者app-eureka-clientOrder(服务别名)使用Rest方式调用服务:
package com.eureka.eurekaclient.Order;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;@RestController
public class OrderController {@Autowiredprivate RestTemplate restTemplate;@RequestMapping("/getOrder")public String getOrder() {// order 使用rpc 远程调用技术 调用 会员服务String memberUrl = "http://app-eureka-clientMember/getMember";String result = "会员服务调用订单服务" + restTemplate.getForObject(memberUrl, String.class);System.out.println("会员服务调用订单服务,result:" + result);return result;}
}
以服务别名方式调用服务提供者接口,这个需要依赖于负载均衡器Ribbon,这就需要在启动类中加上注解@LoadBalanced
3.服务调用实测
服务注册中心:127.0.0.1:8100
服务提供者 :127.0.0.1:8003
服务消费者:127.0.0.1:8002
- 访问服务提供者:127.0.0.1:8003
- 访问服务消费者:127.0.0.1:8002
预期结果
String memberUrl = "http://app-eureka-clientMember/getMember";
String result = "会员服务调用订单服务" + restTemplate.getForObject(memberUrl, String.class);
项目源代码
链接:https://pan.baidu.com/s/1bxP7ZL6fDJdcJ6zscUdN6g
提取码:zmpi
这篇关于Springcloud微服务注册中心-Eureka 2.X(二)——服务消费者调用服务提供者的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!