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 ...
随机推荐
- linux子网掩码优化配置
prefix prefix是前缀的意思,这里指子网掩码的位数. 如255.255.255.0则在ifcfg-eth0的配置文件中:PREFIX=24而NETMASK与PREFIX的作用是一样的,都是配 ...
- sqldeveloper全部导出
点击Tools--Export User Objects 这种方式可以导出当前用户拥有的所有对象,包括表.视图.触发器.同义词等等,对于表,只能导出表结构(建表语句),不能导出数据, 选中要导出的对象 ...
- C# JavaScriptSerializer 自定义序列化
虽然,我个人建议使用Json.Net. 但大家需求不同.遇到一个朋友,他有个需求JavaScriptSerializer并且序列化时,隐藏基类成员. 这里我采用自定义序列化来实现: public st ...
- linux常用命令记录(一)
文件搜索命令 grep在文件中查找字符并输出 grep 字符或字符串 文件目录 grep pub /teach/.txt -c 字符出现总行数 grep .txt -n 行号 grep .txt -i ...
- isPrototypeOf,hasOwnProperty
在看jquery源码的过程中,了解到isPrototypeOf属性.此属性只是Object.prototype的自有属性,即: Object.prototype.hasOwnProperty('isP ...
- 第3篇K8S集群部署
一.利用ansible部署kubernetes准备: 集群介绍 本系列文档致力于提供快速部署高可用k8s集群的工具,并且也努力成为k8s实践.使用的参考书:基于二进制方式部署和利用ansible- ...
- Spring Boot 2.0 常见问题总结(一)
SpringBoot2.x 依赖环境和版本新特性说明 依赖版本 jdk8 以上, Springboot2.x 用 JDK8 , 因为底层是 Spring framework5 . jar 包方式运行 ...
- leetcode-163周赛-1262-可被3整除的最大和
题目描述: 方法一:动态规划 O(N) class Solution: def maxSumDivThree(self, nums: List[int]) -> int: dp = [0, -1 ...
- Java刷题笔记
能用StringBuffer的时候坚决不要用String,因为前者的时间和空间效率都更高. 牛顿法求平方根:随便找一个K,然后不断让 k=(k+x/k)/2;直到K的平方与x之间的差距小于限定值. 斐 ...
- 赋能时空云计算,阿里云数据库时空引擎Ganos上线
随着移动互联网.位置感知技术.对地观测技术的快速发展,时空信息已从传统GIS行业渗透到大众应用及各行各业.从静态POI(兴趣点)到APP位置信息,从导航电子地图到车辆行驶轨迹,从卫星影像到三维城市建模 ...