SpringCloud服务消费有哪几种方式?
一、使用LoadBalancerClient
LoadBalancerClient接口的命名中,可以看出这是一个负载均衡客户端的抽象定义,spring提供了一个实现
org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient
1、pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- spring boot test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2、application.yml
server:
#服务端口号
port: 8080
spring:
application:
#服务名称
name: vis-basic-report
thymeleaf:
cache: false
cloud:
consul:
host: 192.168.12.125
port: 8500
discovery:
#是否需要注册到consul中
register: true
#服务地址直接为IP地址
hostname: 192.168.12.1
management:
endpoints:
web:
exposure:
include: '*'
3、启动类
package com.wzl.springcloud.basic.report;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
@SpringBootApplication
@EnableDiscoveryClient
public class ReportServerApplication {
public static void main(String[] args) {
SpringApplication.run(ReportServerApplication.class, args);
}
}
4、相关实现类
package com.wzl.springcloud.basic.report.service;
import java.util.List;
import com.wzl.springcloud.basic.report.vo.City;
import com.wzl.springcloud.basic.report.vo.WeatherResponse;
public interface WeatherReportService {
// 根据城市ID同步天气
WeatherResponse getDataByCityId(String cityId);
// 根据城市name同步天气
WeatherResponse getDataByCityName(String cityName);
// 获取所有城市列表
List<City> getDataByCities();
}
package com.wzl.springcloud.basic.report.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson.JSON;
import com.wzl.springcloud.basic.report.service.WeatherReportService;
import com.wzl.springcloud.basic.report.vo.City;
import com.wzl.springcloud.basic.report.vo.WeatherResponse;
/**
* LoadBalancer客户端
*/
@Service
public class WeatherReportServiceLoadBalancerClientImpl implements WeatherReportService {
@Autowired
private LoadBalancerClient loadBalancer;
@Override
public WeatherResponse getDataByCityId(String cityId) {
WeatherResponse weatherResponse = null;
ServiceInstance serviceInstance = loadBalancer.choose("vis-basic-weather");
String uri = serviceInstance.getUri().toString() + "/weather/cityId/" + cityId;
// 调用服务接口来获取
ResponseEntity<String> respString = new RestTemplate().getForEntity(uri, String.class);
// 判断ResponseEntity的状态码是否为200,为200时取出strBody
if (respString.getStatusCodeValue() == 200) {
String jsonStr = respString.getBody();
weatherResponse = JSON.parseObject(jsonStr, WeatherResponse.class);
}
return weatherResponse;
}
@Override
public WeatherResponse getDataByCityName(String cityName) {
WeatherResponse weatherResponse = null;
ServiceInstance serviceInstance = loadBalancer.choose("vis-basic-weather");
String uri = serviceInstance.getUri().toString() + "/weather/cityName/" + cityName;
// 调用服务接口来获取
ResponseEntity<String> respString = new RestTemplate().getForEntity(uri, String.class);
// 判断ResponseEntity的状态码是否为200,为200时取出strBody
if (respString.getStatusCodeValue() == 200) {
String jsonStr = respString.getBody();
weatherResponse = JSON.parseObject(jsonStr, WeatherResponse.class);
}
return weatherResponse;
}
@Override
public List<City> getDataByCities() {
List<City> cityList = null;
ServiceInstance serviceInstance = loadBalancer.choose("vis-basic-city");
String uri = serviceInstance.getUri().toString() + "/cities/getList";
// 调用服务接口来获取
ResponseEntity<String> respString = new RestTemplate().getForEntity(uri, String.class);
// 判断ResponseEntity的状态码是否为200,为200时取出strBody
if (respString.getStatusCodeValue() == 200) {
String jsonStr = respString.getBody();
cityList = JSON.parseArray(jsonStr, City.class);
}
return cityList;
}
}
二、使用Ribbon
Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端负载均衡的工具。它是一个基于HTTP和TCP的客户端负载均衡器。它可以通过在客户端中配置ribbonServerList来设置服务端列表去轮询访问以达到均衡负载的作用。
1、pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- spring boot test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2、application.yml
server:
#服务端口号
port: 8080
spring:
application:
#服务名称
name: vis-basic-report
thymeleaf:
cache: false
cloud:
consul:
host: 192.168.12.125
port: 8500
discovery:
#是否需要注册到consul中
register: true
#服务地址直接为IP地址
hostname: 192.168.12.1
management:
endpoints:
web:
exposure:
include: '*'
3、启动类 & RestConfiguration
package com.wzl.springcloud.basic.report;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableFeignClients
public class ReportServerApplication {
public static void main(String[] args) {
SpringApplication.run(ReportServerApplication.class, args);
}
}
package com.wzl.springcloud.basic.report.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestConfiguration {
@Autowired
private RestTemplateBuilder builder;
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return builder.build();
}
}
@LoadBalanced注解表明这个restRemplate开启负载均衡的功能,用外汇返佣LoadBalancerClient配置,并且会替换URL中的服务名称为具体的IP地址
4、相关实现类
package com.wzl.springcloud.basic.report.service;
import java.util.List;
import com.wzl.springcloud.basic.report.vo.City;
import com.wzl.springcloud.basic.report.vo.WeatherResponse;
public interface WeatherReportService {
// 根据城市ID同步天气
WeatherResponse getDataByCityId(String cityId);
// 根据城市name同步天气
WeatherResponse getDataByCityName(String cityName);
// 获取所有城市列表
List<City> getDataByCities();
}
package com.wzl.springcloud.basic.report.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson.JSON;
import com.wzl.springcloud.basic.report.service.WeatherReportService;
import com.wzl.springcloud.basic.report.vo.City;
import com.wzl.springcloud.basic.report.vo.WeatherResponse;
/**
* Ribbon客户端
*/
@Service
public class WeatherReportServiceRibbonImpl implements WeatherReportService {
@Autowired
// 对rest客户端的封装
private RestTemplate restTemplate;
@Override
public WeatherResponse getDataByCityId(String cityId) {
WeatherResponse weatherResponse = null;
String uri = "http://vis-basic-weather/weather/cityId/" + cityId;
// 调用服务接口来获取
ResponseEntity<String> respString = restTemplate.getForEntity(uri, String.class);
// 判断ResponseEntity的状态码是否为200,为200时取出strBody
if (respString.getStatusCodeValue() == 200) {
String jsonStr = respString.getBody();
weatherResponse = JSON.parseObject(jsonStr, WeatherResponse.class);
}
return weatherResponse;
}
@Override
public WeatherResponse getDataByCityName(String cityName) {
WeatherResponse weatherResponse = null;
String uri = "http://vis-basic-weather/weather/cityName/" + cityName;
// 调用服务接口来获取
ResponseEntity<String> respString = restTemplate.getForEntity(uri, String.class);
// 判断ResponseEntity的状态码是否为200,为200时取出strBody
if (respString.getStatusCodeValue() == 200) {
String jsonStr = respString.getBody();
weatherResponse = JSON.parseObject(jsonStr, WeatherResponse.class);
}
return weatherResponse;
}
@Override
public List<City> getDataByCities() {
List<City> cityList = null;
String uri = "http://vis-basic-city/cities/getList";
// 调用服务接口来获取
ResponseEntity<String> respString = restTemplate.getForEntity(uri, String.class);
// 判断ResponseEntity的状态码是否为200,为200时取出strBody
if (respString.getStatusCodeValue() == 200) {
String jsonStr = respString.getBody();
cityList = JSON.parseArray(jsonStr, City.class);
}
return cityList;
}
}
SpringCloud服务消费有哪几种方式?的更多相关文章
- XFire构建服务端Service的两种方式(转)
XFire构建服务端service的两种方式,一是用xfire构建,二是和spring集成构建. 一,xifre构建,确保把xfire的jar包导入到工程中或classpath. 1,service的 ...
- XFire构建服务端Service的两种方式
1.原声构建: 2.集成spring构建 http://blog.csdn.net/carefree31441/article/details/4000436XFire构建服务端Service的两种方 ...
- SpringCloud系列-整合Hystrix的两种方式
Hystrix [hɪst'rɪks],中文含义是豪猪,因其背上长满棘刺,从而拥有了自我保护的能力.本文所说的Hystrix是Netflix开源的一款容错框架,同样具有自我保护能力. 本文目录 一.H ...
- kbmmw 做REST 服务签名认证的一种方式
一般对外提供提供REST 服务,由于信息安全的问题, 都要采用签名认证,今天简单说一下在KBMMW 中如何 实现简单的签名服务? 整个签名服务,模仿阿里大鱼的认证方式,大家可以根据实际情况自己修改. ...
- WCF服务使用(IIS+Http)和(Winform宿主+Tcp)两种方式进行发布
1.写在前面 刚接触WCF不久,有很多地方知其然不知其所以然.当我在[创建服务->发布服务->使用服务]这一过程出现过许多问题.如客户端找不到服务引用:客户端只在本机环境中才能访问服务,移 ...
- 使用RestTemplate进行服务调用的几种方式
首先我们在名为MSG的服务中定义一个简单的方法 @RestController public class ServerController { @GetMapping("/msg" ...
- Servlet实现的三种方式
实现Servlet的三种方式:一个实现,两个继承 /*========================================== * servlet的执行过程: * 1.创建servlet对 ...
- 创建servlet的三种方式
第一种方式,实现Servlet接口 package com.example.servlet; import java.io.IOException; import javax.servlet.Serv ...
- SparkStreaming消费kafka中数据的方式
有两种:Direct直连方式.Receiver方式 1.Receiver方式: 使用kafka高层次的consumer API来实现,receiver从kafka中获取的数据都保存在spark exc ...
随机推荐
- 实现一个EventEmitter类,这个类包含以下方法: on/ once/fire/off
实现一个EventEmitter类,这个类包含以下方法: on(监听事件,该事件可以被触发多次)- once(也是监听事件,但只能被触发一次)- fire(触发指定的事件)- off(移除指定事件的某 ...
- ubuntu 环境 cross compile 交叉编译 ARM Qt 集成 opencv
Qt 的版本众多,交叉编译Qt可以下载 最新的 Qt 5.11,在 qtbase/mkspecs/devices/ 下找到你对应开发板的配置文件, 拷贝出来, 选择一版适用当前交叉编译工具链的版本,这 ...
- Codeforces 1149D 最短路 状压DP
题意及思路:https://blog.csdn.net/yzyyylx/article/details/90145400 这题主要巧妙在分析了最短路算法的性质,得出大小小于等于3的连通块一定不会被再次 ...
- 神奇的Android Studio Template(转)
转自:http://blog.csdn.net/lmj623565791/article/details/51592043 本文已授权微信公众号:鸿洋(hongyangAndroid)在微信公众号平台 ...
- Linux系统关闭对ping命令做响应。
1.测试 ping 192.168.10.5 可以正常ping通, 2,修改 /proc/sys/net/ipv4/icmp_echo_ignore_all 文件的值=1 3.在测试 已经ping不 ...
- 将中国标准时间)转化为yyyy-MM-dd
有两种方法: 1. ]); ) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds ...
- Java中udp/tcp的发送和接收
InetAddress UDP例程: 发送数据: 接收数据: 结果: TCP例程: 发送数据: 接收数据: 结果:
- Web前端/全栈核心(html5/css3/js/vue/react/angular/es6/node)观看笔记
a标签中的超链接,需要加 http:// 否则会出现页面找不到. iframe中添加a标签,a标签中的target属性可以控制即将打开的页面,在那个位置显示. _blank 在新窗口中打开被 ...
- SQL SELECT TOP, LIMIT, ROWNUM
SQL SELECT TOP, LIMIT, ROWNUM SQL SELECT TOP 子句 SELECT TOP 子句用于指定要返回的记录数量. SELECT TOP子句在包含数千条记录的大型表上 ...
- Android中对消息机制(Handler)的再次解读
今天遇到一些关于在子线程中操作Handler的问题,感觉又要研究源代码了,但是关于Handler的话,我之前研究过,可以参考这篇文章:http://blog.csdn.net/jiangwei0910 ...