什麼是微服務?什麼是SpringCloud? 微服務是一種架構的模式,它提倡將一個應用程式劃分成很多個微小的服務,服務與服務之間相互協調、相互配合。每個服務運行都是一個獨立的進程,服務與服務之間採用輕量級的通訊機制相互溝通。簡單的來說就是將一個龐大的複雜的單體應用進行劃分成n多個微小的服務(一個服務 ...
什麼是微服務?什麼是SpringCloud?
微服務是一種架構的模式,它提倡將一個應用程式劃分成很多個微小的服務,服務與服務之間相互協調、相互配合。每個服務運行都是一個獨立的進程,服務與服務之間採用輕量級的通訊機制相互溝通。簡單的來說就是將一個龐大的複雜的單體應用進行劃分成n多個微小的服務(一個服務負責一個業務),各個微服務都被獨立的部署。
微服務與集群的區別是,微服務的每一個部署的服務都是不相同的,而集群部署的每一個服務都是相同的。
Spring Cloud是一個微服務框架,相比Dubbo等RPC框架,Spring Cloud提供的全套的分散式系統解決方案。它是在SpringBoot的基礎上構建的。SpringCloud的五大神獸分別是Eureka、Ribbon、Feign、Hystrix、Zuul。
環境搭建
版本說明
springboot:2.0.3
springcloud:Finchley
創建一個父工程(maven項目)
選擇maven,點擊next
然後點擊完成
修改父工程pom.xml
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.lzh</groupId> <artifactId>my-springcloud-01</artifactId> <packaging>pom</packaging> <version>1.0-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <junit.version>4.12</junit.version> <log4j.version>1.2.17</log4j.version> <lombok.version>1.16.18</lombok.version> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Finchley.RELEASE</version> <!--<version>Dalston.SR1</version>--> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.0.3.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.0.4</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.31</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> </dependencies> </dependencyManagement> <build> <finalName>microservicecloud</finalName> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> </resource> </resources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <configuration> <delimiters> <delimit>$</delimit> </delimiters> </configuration> </plugin> </plugins> </build> </project>
創建子工程(maven項目)
工程名稱:microservice-consumer-80
pom.xml文件
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>my-springcloud-01</artifactId> <groupId>com.lzh</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>microservice-consumer-80</artifactId> <dependencies> <dependency> <groupId>com.lzh</groupId> <artifactId>microservice-api</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <!-- 整合ribbon --> <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> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> </dependencies> </project>
編碼實現
在主啟動類上加上@EnableDiscoveryClient註解
創建一個配置文件ConfigBean.java,new一個RestTemplate遠程調用模板,加入@LoadBalanced註解,開啟負載均衡
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; /** * @author lzh * create 2019-11-05-9:58 */ @Configuration public class ConfigBean { @Bean //加入負載均衡 //Spring Cloud Ribbon是基於Netflix Ribbon實現的一套客戶端 負載均衡的工具 @LoadBalanced public RestTemplate getRestTemplate(){ return new RestTemplate(); } }
在服務層DeptServiceImpl.java類中用RestTemplate模板工具調用,這裡使用服務名稱調用,如果服務名稱相同,則會進行順序輪詢調用
import com.lzh.cloud.model.Dept; import com.lzh.cloud.service.DeptService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.util.List; /** * @author lzh * create 2019-11-05-10:27 */ @Service public class DeptServiceImpl implements DeptService { /** * 使用restTemplate訪問restful介面非常的簡單粗暴無腦。 * (url, requestMap, ResponseBean.class)這三個參數分別代表 * REST請求地址、請求參數、HTTP響應轉換被轉換成的對象類型。 */ @Autowired private RestTemplate restTemplate; //private static final String REST_URL_PREFIX = "http://localhost:8001"; private static final String REST_URL_PREFIX = "http://MICROSERVICECLOUD-DEPT"; @Override public boolean add(Dept dept) { return restTemplate.postForObject(REST_URL_PREFIX + "/dept/add", dept, Boolean.class); } @Override public Dept get(Long id) { return restTemplate.getForObject(REST_URL_PREFIX + "/dept/get/" + id, Dept.class); } @Override public List<Dept> list() { return restTemplate.getForObject(REST_URL_PREFIX + "/dept/list/", List.class); } @Override public Object discovery() { return restTemplate.getForObject(REST_URL_PREFIX + "/dept/discovery", Object.class); } }
自定義輪詢規則
在主啟動類的前一個包創建一個配置MySelRule類,註意不要跟主啟動類同包或者在主啟動類的子包中創建
import com.netflix.loadbalancer.IRule; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author lzh * create 2019-05-19-17:10 */ @Configuration public class MySelfRule { @Bean public IRule myRule(){ //return new RandomRule(); //Ribbon預設是輪詢,我自定義為隨機 //return new RoundRobinRule(); //Ribbon預設是輪詢,我自定義為隨機 return new RandomRule_LZH(); // 我自定義為每台機器5次 } }
參照源碼,自定義輪詢演算法RandomRule_LZH.java
import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.AbstractLoadBalancerRule; import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.loadbalancer.Server; import java.util.List; public class RandomRule_LZH extends AbstractLoadBalancerRule { // total = 0 // 當total==5以後,我們指針才能往下走, // index = 0 // 當前對外提供服務的伺服器地址, // total需要重新置為零,但是已經達到過一個5次,我們的index = 1 // 分析:我們5次,但是微服務只有8001 8002 8003 三台,OK? // private int total = 0; // 總共被調用的次數,目前要求每台被調用5次 private int currentIndex = 0; // 當前提供服務的機器號 public Server choose(ILoadBalancer lb, Object key) { if (lb == null) { return null; } Server server = null; while (server == null) { if (Thread.interrupted()) { return null; } List<Server> upList = lb.getReachableServers(); List<Server> allList = lb.getAllServers(); int serverCount = allList.size(); if (serverCount == 0) { /* * No servers. End regardless of pass, because subsequent passes only get more * restrictive. */ return null; } // int index = rand.nextInt(serverCount);// java.util.Random().nextInt(3); // server = upList.get(index); // private int total = 0; // 總共被調用的次數,目前要求每台被調用5次 // private int currentIndex = 0; // 當前提供服務的機器號 if (total < 5) { server = upList.get(currentIndex); total++; } else { total = 0; currentIndex++; if (currentIndex >= upList.size()) { currentIndex = 0; } } if (server == null) { /* * The only time this should happen is if the server list were somehow trimmed. * This is a transient condition. Retry after yielding. */ Thread.yield(); continue; } if (server.isAlive()) { return (server); } // Shouldn't actually happen.. but must be transient or a bug. server = null; Thread.yield(); } return server; } @Override public Server choose(Object key) { return choose(getLoadBalancer(), key); } @Override public void initWithNiwsConfig(IClientConfig clientConfig) { // TODO Auto-generated method stub } }
最後不要忘了在主啟動類加上註解,使用自定義輪詢演算法configuration = MySelfRule.class
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; /** * @author lzh * create 2019-11-04-22:26 */ @SpringBootApplication @EnableEurekaClient //自定義負載均衡規則 //在啟動該為服務的時候就能去載入我們的自定義Ribbon配置類,從而使配置生效 //configuration = MySelfRule.class 把MySelfRule配置類載入進容器 @RibbonClient(name = "MICROSERVICECLOUD-DEPT",configuration = MySelfRule.class) @EnableDiscoveryClient public class MyConsumerApplication_80 { public static void main(String[] args) { SpringApplication.run(MyConsumerApplication_80.class); } }
代碼
github:https://github.com/LZHDonald/my-springcloud-01/tree/master/microservice-consumer-80