springcloud 入门系列(二)-eureka服务调用

上篇文章我们了解了如何搭建springcloud 高可用注册中心(eureka注册中心高可用),本篇我们来了解,如何进行服务的调用。

 

首先,我们先来创建我们的服务提供者:

pom依赖:

 

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

springboot 配置文件:

 

 

spring:
application:
name: helloService
eureka:
client:
service-url:
defaultZone: http://localhost:8080/eureka

server:
port: 8081
management:
endpoint:
health:
enabled: true
refresh:
enabled: true

 

配置中的 eureka.client.service-url.defaultZone是我们的注册中心地址。

然后是服务实现:

 

@RestController
@Slf4j
public class HelloService {

@GetMapping("hello")
public String hello(String name) throws InterruptedException {
log.info("hello:{}-线程睡眠:{}",name);
Thread.sleep(5000);
return "hello"+name;
}

@PostMapping("hello2")
public String hello2(@RequestBody com.ethan.springclod.api.vo.User user) throws InterruptedException {
log.info("hello:{}",user);
// Thread.sleep(1000);
return user.toString();
}

@PostMapping("hello3")
public String hello3( User user) {
log.info("hello:{}",user);
return user.toString();
}

}

服务就是一个简单的springmvc 的controller,和我们的以往的springmvc 没有任何的不同。

然后我们启动注册中心,以及服务提供者,然后查看注册中心:

我们发现,helloservice 已经被注册成功。注册中心的服务名称就是我们在配置文件中定义的spring.application.name.

 

下面我们来搭建服务的调用者:

pom:

 

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

 

spring 配置文件:

 

server.port=8083
spring.application.name=helloService-customer
eureka.client.service-url.defaultZone = http://localhost:8080/eureka,http://localhost:8070/eureka

 

然后是服务调用示例:

 

 

@Autowired
private RestTemplate restTemplate;

/**
* 坑点:使用 服务名调用服务,必须@LoadBalanced 注解
*
* @param name
* @return
*/
@GetMapping("hello")
public String hello(String name) {
String responseEntity = restTemplate.getForObject("http://HELLOSERVICE/hello?name={1}", String.class, name);
log.info("hello service :{}", responseEntity);
return responseEntity;
}

这里我们使用的是spring 提供的 RestTemplate 进行http请求调用。

然后我们关注下请求的url:

 

http://HELLOSERVICE/hello?name={1}

这里我们没有看到ip以及端口等信息,这里的 HELLOSERVICE,就是我们注册中心的服务名,eureka 可以让我们直接通过服务名进行服务的调用,eureka 会对服务名进行解析,最终生成目标访问地址。

我们启动服务消费者;并且在刘燃气输入 http://localhost:8083/hello?name=米记小匠,如图:

以及控制台的日志输出:

2019-07-03 15:59:44.495  INFO 6236 --- [nio-8083-exec-4] c.e.s.h.HelloController                  : hello service :hello米记小匠

至此说明我们的eureka 服务调用成功。

下篇我们会讲服务的负载均衡组件:ribbon.

欢迎关注本公众号,参与我们的学习讨论!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值