在上一篇文章Eureka服务注册发现实例中,我们演示了微服务的注册与发现,在此基础上,这篇文章我们演示通过restTemplate来实现对springcloud微服务的调用。
1用spring boot新建一个消费者工程,引入eureka依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
2修改配置文件
#微服务端口
server.port=2200
#微服务应用名
spring.application.name=consumer
#表示表示是否从EurekaServer获取注册信息,默认为true
eureka.client.fetch-registry=true
eureka.client.service-url.defaultZone=http://localhost:8260/eureka/
3修改启动文件
修改启动文件ConsumerApplication.java,引入注解@EnableDiscoveryClient,创建一个restTemplate Bean,注意添加@LoadBalanced这个注解,否则调用的时候报java.net.UnknownHostException:,代码如下:
package com.yuxiaolong;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@EnableDiscoveryClient
@SpringBootApplication
public class ConsumerApplication {
@Bean(value = "restTemplate")
@LoadBalanced
RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
}
4写一个controller类调用服务端方法
在controller类中调用wojia服务端中的微服务,代码如下:
package com.yuxiaolong.controller;
import com.yuxiaolong.model.ModuleDO;
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;
import java.util.Arrays;
import java.util.List;
/**
* Created by yuxl on 2019/3/1.
*/
@RestController
@RequestMapping(value = "/module")
public class ModuleController {
@Autowired
private RestTemplate restTemplate;
@RequestMapping(value = "/list")
public List<ModuleDO> listModules(){
ModuleDO[] moduleDOS = this.restTemplate.getForObject("http://wojia/module/list",ModuleDO[].class);
return Arrays.asList(moduleDOS);
}
}
5启动服务,请求接口
依次启动上一篇文章Eureka服务注册发现实例中提到的Eureka注册中心和微服务提供者wojia,再启动本文中的消费者服务consumer,在浏览器中输入请求http://localhost:2200/module/list,返回结果如下:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnLxMjN4UTOyETMxAzMwkTMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
微信扫下面二维码添加公众号议码评川,可获取java web、大数据、人工智能等相关学习资料。