目錄
-
- Ribbon負載均衡介紹
- 用戶端內建Ribbon負載均衡
- 聲明式服務調用Feign
Ribbon負載均衡介紹
上篇博文寫了eureka服務的注冊和發現,以及它的叢集,但是關于叢集調用服務提供者并沒有講,也就是當服務提供者其中一個節點挂掉,并沒有介紹怎麼去處理以及避免
Ribbon是Netflix釋出的負載均衡器,它有助于控制HTTP和TCP的用戶端的行為。為Ribbon配置服務提供者位址後,Ribbon就可基于某種負載均衡算法,自動地幫助服務消費者去請求。Ribbon預設為我們提供了很多負載均衡算法,例如輪詢、随機等。當然,我們也可為Ribbon實作自定義的負載均衡算法. 在Spring Cloud中,當Ribbon與Eureka配合使用時,Ribbon可自動從Eureka Server擷取服務提供者位址清單,并基于負載均衡算法,請求其中一個服務提供者執行個體。展示了Ribbon與Eureka配合使用時的架構
用戶端內建Ribbon負載均衡
Ribbon是用戶端負載均衡,是以肯定內建再消費端,也就是consumer端
在用戶端添加pom依賴
<!--ribbon相關依賴-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
yml配置
server:
port: 80
context-path: /
eureka:
client:
service-url:
defaultZone: http://eureka2001.xiaoyang.com:2001/eureka/,http://eureka2002.xiaoyang.com:2002/eureka/,http://eureka2003.xiaoyang.com:2003/eureka/
register-with-eureka: false
SpringCloudConfig 負載均衡配置
package com.xiaoyang.microservicestudentconsumer80.config;
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 SpringCloudConfig {
// 消費者通路生産者代碼(服務a和伺服器b通信)
@LoadBalanced//引入ribbon負載均衡
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
因為和eureka整合,是以啟動類StudentConsumerApplication_80 加個注解 @EnableEurekaClient
package com.xiaoyang.microservicestudentconsumer80;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@EnableEurekaClient
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class MicroserviceStudentConsumer80Application {
public static void main(String[] args) {
SpringApplication.run(MicroserviceStudentConsumer80Application.class, args);
}
}
這裡還有一個,要修改下StudentConsumerController的PRE_HOST,改成指定的微服務應用名稱;
當然這裡要先在服務提供者microservice-student-provider-1001(或者三合一的服務提供配置中)的application.yml加下配置,指定下應用名稱:
我們的微服務應用名稱是 microservice-student
是以服務調用者這邊的控制器裡PRE_HOST改成 http://MICROSERVICE-STUDENT即可;
MICROSERVICE-STUDENT為Eureka注冊中心的應用名稱
前面搭建了初步例子,但是還沒實作真正負載均衡,我們這裡要先搞三個服務提供者叢集,然後才能示範負載均衡,以及負載均衡政策
三合一:
---
server:
port: 1001
context-path: /
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
username: xiaoyang
password: 123
jpa:
hibernate:
ddl-auto: update
show-sql: true
application:
name: microservice-student
profiles: provider-1001
eureka:
instance:
hostname: localhost
appname: microservice-student
instance-id: microservice-student:1001
prefer-ip-address: true
client:
service-url:
defaultZone: http://eureka2001.xiaoyang.com:2001/eureka/,http://eureka2002.xiaoyang.com:2002/eureka/,http://eureka2003.xiaoyang.com:2003/eureka/
info:
groupId: com.xiaoyang.testSpringcloud
artifactId: microservice-student-provider-1001
version: 1.0-SNAPSHOT
userName: http://xiaoyang.com
phone: 123456
---
server:
port: 1002
context-path: /
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
username: xiaoyang
password: 123
jpa:
hibernate:
ddl-auto: update
show-sql: true
application:
name: microservice-student
profiles: provider-1002
eureka:
instance:
hostname: localhost
appname: microservice-student
instance-id: microservice-student:1002
prefer-ip-address: true
client:
service-url:
defaultZone: http://eureka2001.xiaoyang.com:2001/eureka/,http://eureka2002.xiaoyang.com:2002/eureka/,http://eureka2003.xiaoyang.com:2003/eureka/
info:
groupId: com.xiaoyang.testSpringcloud
artifactId: microservice-student-provider-1002
version: 1.0-SNAPSHOT
userName: http://xiaoyang.com
phone: 123456
---
server:
port: 1003
context-path: /
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
username: xiaoyang
password: 123
jpa:
hibernate:
ddl-auto: update
show-sql: true
application:
name: microservice-student
profiles: provider-1003
eureka:
instance:
hostname: localhost
appname: microservice-student
instance-id: microservice-student:1003
prefer-ip-address: true
client:
service-url:
defaultZone: http://eureka2001.xiaoyang.com:2001/eureka/,http://eureka2002.xiaoyang.com:2002/eureka/,http://eureka2003.xiaoyang.com:2003/eureka/
info:
groupId: com.xiaoyang.testSpringcloud
artifactId: microservice-student-provider-1003
version: 1.0-SNAPSHOT
userName: http://xiaoyang.com
phone: 123456
controller
package com.xiaoyang.microservicestudentprovider.controller;
import com.xiaoyang.microservicecommon.entity.Student;
import com.xiaoyang.microservicestudentprovider.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/student")
public class StudentProviderController {
@Autowired
private StudentService studentService;
@Value("${server.port}")
private String port;
@RequestMapping("/ribbon")
public String ribbon() {
return "工号【" + port + "】正在為您服務";
}
@PostMapping(value = "/save")
public boolean save(Student student) {
try {
studentService.save(student);
return true;
} catch (Exception e) {
return false;
}
}
@GetMapping(value = "/list")
public List<Student> list() {
return studentService.list();
}
@GetMapping(value = "/get/{id}")
public Student get(@PathVariable("id") Integer id) {
return studentService.findById(id);
}
@GetMapping(value = "/delete/{id}")
public boolean delete(@PathVariable("id") Integer id) {
try {
studentService.delete(id);
return true;
} catch (Exception e) {
return false;
}
}
}
現在就可以啟動服務進行檢視了
多重新整理幾次 看控制台,我們看到 有預設的輪詢政策,通路對應的服務提供者(負載均衡會輪詢服務提供者的節點)
但是這種預設的輪詢政策肯定是不能滿足實際需求的,比如有3個服務提供者,突然挂了一個,這樣的話,預設輪詢 ,總有1/3的機率通路失敗; 是以我們看下ribbon預設給我們提供的政策有哪些:
消費者配置類
/**
* 自定義調用規則(服務提供者掉線後不再調用,解決輪詢問題)
* @return
*/
@Bean
public IRule myRule(){
return new RetryRule();
// return new RandomRule();
}
我們可以同時啟動三個服務,斷掉一個01服務節點,當負載均衡的輪詢機制重新整理到01時,則不會将報錯資訊顯示,如果沒有配置重試政策機制,則會在通路頁面顯示報錯資訊。當01節點重新啟動服務,輪詢機制會它重新加回輪詢中,此時這個節點又可以通路了…
聲明式服務調用Feign
前面Ribbon調用服務提供者,我們通過restTemplate調用,缺點是,多個地方調用,同一個請求要寫多次,不友善統一維護,這時候Feign來了,就直接把請求統一搞一個service作為FeignClient,然後其他調用Controller需要用到的,直接注入service,直接調用service方法即可;同時Feign整合了Ribbon和Eureka,是以要配置負載均衡的話,直接配置Ribbon即可,無其他特殊地方;當然Fiegn也整合了服務容錯保護,斷路器Hystrix
應用:
在common項目裡建一個service(實際項目肯定是多個service)作為Feign用戶端,用Feign用戶端來調用伺服器提供者,當然可以配置負載均衡;Feign用戶端定義的目的,就是為了友善給其他項目調用
pom.xml引入Feign依賴
<!--引入Feign依賴-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
建StudentClientService接口
package com.xiaoyang.microservicecommon.service;
import com.xiaoyang.microservicecommon.entity.Student;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
/**
* Student Feign接口用戶端
* @author Administrator
*
*/
@FeignClient(value="MICROSERVICE-STUDENT")
public interface StudentClientService {
/**
* 根據id查詢學生資訊
* @param id
* @return
*/
@GetMapping(value="/student/get/{id}")
public Student get(@PathVariable("id") Integer id);
/**
* 查詢學生資訊
* @return
*/
@GetMapping(value="/student/list")
public List<Student> list();
/**
* 添加或者修改學生資訊
* @param student
* @return
*/
@PostMapping(value="/student/save")
public boolean save(Student student);
/**
* 根據id删除學生資訊
* @return
*/
@GetMapping(value="/student/delete/{id}")
public boolean delete(@PathVariable("id") Integer id);
@RequestMapping("/student/ribbon")
public String ribbon();
}
microservice-student-consumer-feign-80引入和原microservice-student-consumer–80一樣的配置(多了一個Feign依賴)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.xiaoyang</groupId>
<artifactId>microservice</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>microservice-student-consumer-feign-80</artifactId>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<!-- 修改後立即生效,熱部署 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<!--ribbon相關依賴-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>com.xiaoyang</groupId>
<artifactId>microservice-common</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<!--引入Feign依賴-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
啟動類加上注解
controller
package com.xiaoyang.microservicestudentconsumerfeign80.controller;
import com.xiaoyang.microservicecommon.entity.Student;
import com.xiaoyang.microservicecommon.service.StudentClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.List;
@RestController
@RequestMapping("/student")
public class StudentConsumerController {
@Autowired
private StudentClientService studentClientService;
@Autowired
private RestTemplate restTemplate;
@PostMapping(value = "/save")
private boolean save(Student student) {
return studentClientService.save(student);
}
@GetMapping(value = "/list")
public List<Student> list() {
return studentClientService.list();
}
@GetMapping(value = "/get/{id}")
public Student get(@PathVariable("id") Integer id) {
return studentClientService.get(id);
}
@GetMapping(value = "/delete/{id}")
public boolean delete(@PathVariable("id") Integer id) {
try {
studentClientService.delete(id);
return true;
} catch (Exception e) {
return false;
}
}
@RequestMapping("/ribbon")
public String ribbon(){
return studentClientService.ribbon();
}
}
over…