一、使用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服务消费有哪几种方式?的更多相关文章

  1. XFire构建服务端Service的两种方式(转)

    XFire构建服务端service的两种方式,一是用xfire构建,二是和spring集成构建. 一,xifre构建,确保把xfire的jar包导入到工程中或classpath. 1,service的 ...

  2. XFire构建服务端Service的两种方式

    1.原声构建: 2.集成spring构建 http://blog.csdn.net/carefree31441/article/details/4000436XFire构建服务端Service的两种方 ...

  3. SpringCloud系列-整合Hystrix的两种方式

    Hystrix [hɪst'rɪks],中文含义是豪猪,因其背上长满棘刺,从而拥有了自我保护的能力.本文所说的Hystrix是Netflix开源的一款容错框架,同样具有自我保护能力. 本文目录 一.H ...

  4. kbmmw 做REST 服务签名认证的一种方式

    一般对外提供提供REST 服务,由于信息安全的问题, 都要采用签名认证,今天简单说一下在KBMMW 中如何 实现简单的签名服务? 整个签名服务,模仿阿里大鱼的认证方式,大家可以根据实际情况自己修改. ...

  5. WCF服务使用(IIS+Http)和(Winform宿主+Tcp)两种方式进行发布

    1.写在前面 刚接触WCF不久,有很多地方知其然不知其所以然.当我在[创建服务->发布服务->使用服务]这一过程出现过许多问题.如客户端找不到服务引用:客户端只在本机环境中才能访问服务,移 ...

  6. 使用RestTemplate进行服务调用的几种方式

    首先我们在名为MSG的服务中定义一个简单的方法 @RestController public class ServerController { @GetMapping("/msg" ...

  7. Servlet实现的三种方式

    实现Servlet的三种方式:一个实现,两个继承 /*========================================== * servlet的执行过程: * 1.创建servlet对 ...

  8. 创建servlet的三种方式

    第一种方式,实现Servlet接口 package com.example.servlet; import java.io.IOException; import javax.servlet.Serv ...

  9. SparkStreaming消费kafka中数据的方式

    有两种:Direct直连方式.Receiver方式 1.Receiver方式: 使用kafka高层次的consumer API来实现,receiver从kafka中获取的数据都保存在spark exc ...

随机推荐

  1. SpringBoot - @ControllerAdvice 处理异常

    在Spring 3.2中,新增了@ControllerAdvice.@RestControllerAdvice 注解,可以用于定义@ExceptionHandler.@InitBinder.@Mode ...

  2. Internet History 课程笔记

    课程地址:https://www.coursera.org/learn/internet-history 科学|上网可解决视频加载不出来的问题 Week 1 High Stakes Research ...

  3. Magento笔记/记录(1)

    1.Magento eav_attribute表中source如何指定自定义数据来源  如果你引用的类名为yebihai_usermanage_model_entity_school你必须完整的给出地 ...

  4. delphi 设备函数GetDeviceCaps函数

    {说明:以下内容来源于网络,修改多处错误所得 2019.10.04 } GetDeviceCaps 函数功能:该函数检索指定设备的设备指定信息.该函数经常用在操作打印机等设备中.函数原型:int Ge ...

  5. Delphi获取指定文件的版本号

    获取指定文件的版本号 方式一: function GetFileVersion(FileName: string): string; type PVerInfo = ^TVS_FIXEDFILEINF ...

  6. 剑指offer——丑数(c++)

    题目描述只包含质因子2.3和5的数称作丑数(UglyNumber).例如6.8都是丑数,但14不是,因为它包含质因子7,习惯上我们把1当做是第一个丑数.求按从小到大的顺序的第N个丑数. 思路:1.逐个 ...

  7. postgreSQL的主外键

    --添加主键 alter table cities add PRIMARY KEY(name); --添加外键 alter table weather add FOREIGN key(city) RE ...

  8. ping命令的应用

    Ping命令是工作在 TCP/IP网络体系结构中应用层的一个服务命令, 主要功能是向特定的目的主机发送 ICMP(Iternet Control Message Protocol 因特网报文控制协议) ...

  9. VC++ 2010 创建高级Ribbon界面详解(3)

    3.工具栏 在传统的菜单式界面中,工具栏作为菜单的有益补充,被广泛使用.我们通过将一些常用命令放置到工具栏上,可以让用户直观而快速地访问到常用功能,提高了效率.在Ribbon界面中,工具栏得到了进一步 ...

  10. css3继承

    不可继承的:display.margin.border.padding.background.height.min-height.max- height.width.min-width.max-wid ...