上一篇寫到關於SpringCloudEureka的相關知識:SpringCloud服務治理Eureka。咱們實現的服註冊中心,以及服務提供者。接下來記錄關於服務消費,以及客戶端負載均衡器Ribbon的簡單使用和配置。在使用Ribbon以前,先看看怎麼調用服務吧。java
在上一篇的基礎之上,建立一個service-user
的微服務。這個微服我使用了h2數據庫來保存數據,因此須要在配置文件中添加關於數據庫的配置以及在pom文件中添加依賴,<!--more-->
application.ymlgit
server: port: 40000 spring: application: name: user-service #=========================================================== # 數據庫配置 #=========================================================== jpa: show-sql: true hibernate: ddl-auto: none generate-ddl: false datasource: platform: h2 schema: classpath:schema.sql data: classpath:data.sql #=========================================================== # eureka配置 #=========================================================== eureka: client: serviceUrl: defaultZone: http://localhost:8888/eureka/ instance: prefer-ip-address: true instance-id: ${spring.application.name}:${server.port}
pom.xmlweb
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> </dependencies>
而後編寫數據庫文件初始化數據;
schema.sqlspring
DROP TABLE user if EXISTS ; create table user ( id int generated by DEFAULT as IDENTITY, username VARCHAR (40), age INT(3), PRIMARY KEY (id) );
data.sqlsql
insert into user (id,username,age) values (1,'張三',20); insert into user (id,username,age) values (2,'李四',25); insert into user (id,username,age) values (3,'王五',23); insert into user (id,username,age) values (4,'趙六',30);
User實體類,這裏使用了lombok
工具數據庫
@Entity @Data public class User implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column private String username; @Column private int age; }
而後建立UserRepository
和UserController
,在UserController
中添加一個根據id查詢的接口:app
@Autowired private UserRepository userRepository; @GetMapping("/user/{id}") public User findById(@PathVariable("id") Long id){ return userRepository.findOne(id); }
在SpringBoot
入口類上添加@EnableEurekaClient
註解負載均衡
@EnableEurekaClient @SpringBootApplication public class UserApplication { public static void main(String[] args) { SpringApplication.run(UserApplication.class, args); } }
最終的項目結構:dom
啓動項目,訪問:http://localhost:40000/user/1
spring-boot
這裏直接修改上一篇service-article
服務,用service-article
服務來調用service-user
服務。因此須要修改service-article
,新增User
對象和ArticleController
,在ArticleController
中添加一個查詢接口。
這裏調用服務都是使用RestTemplate
,因此先在入口內中註冊註冊RestTemplate
,
@SpringBootApplication @EnableEurekaClient public class ArticleApplication { @Bean public RestTemplate restTemplate(){ return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(ArticleApplication.class, args); } }
User實體,能夠直接拷貝user微服務的實體類去掉註解便可,由於這裏不是持久化對象。
@Data public class User implements Serializable { private Long id; private String username; private int age; }
ArticleController
@RestController public class ArticleController { @Autowired private RestTemplate restTemplate; @GetMapping("/a/u/{id}") public User getUser(@PathVariable("id") Long id){ return restTemplate.getForObject("http://localhost:40000/user/{1}",User.class,id); } }
啓動服務,訪問:http://localhost:30000/a/u/2
SpringCloudRibbon是一個基於HTTP和TCP的客戶端負載均衡工具。是基於Netfix Ribbon實現的。SpringCloud將其封裝,可讓咱們輕鬆的將面向服務的REST模板自動轉換成客戶端負載均衡的服務調用。
修改article-service
,
添加依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
在註冊RestTemplate
方法上添加@LoadBalanced
註解開啓客戶端負載均衡,而後修改請求的URL,直接使用服務名請求,這裏可以直接使用服務名,是由於在SpringCloudRibbon中有一個攔截器,他可以在實際調用的時候自動的選取服務實例,並將實際請求的ip地址替換這裏的服務名。詳細介紹能夠查看DD大佬的書:<<SpringCloud微服務實戰>>
@GetMapping("/a/u/{id}") public User getUser(@PathVariable("id") Long id){ return restTemplate.getForObject("http://USER-SERVICE:40000/user/{1}",User.class,id); }
最後爲了測試負載均衡,咱們須要開啓多個USER-SERVICE服務實例;在USER-SERVICE中添加application-pree1.yml
和application-pree2.yml
,具體配與application.yml同樣,只要修改server.port
,這裏分別是40001和40002。而後打包服務,分別啓動兩個服務
java -jar user-0.0.1-SNAPSHOT.jar --spring.profiles.active=pree1 java -jar user-0.0.1-SNAPSHOT.jar --spring.profiles.active=pree2
在註冊中心能夠看到三個USER-SERVICE服務:
最後啓動ARTICLE-SERVICE,並訪問接口。刷新幾回頁面,發現三個服務都會打印數據庫語句,這裏調用方式爲線性輪詢
當咱們在SpringBoot項目中添加SpringCloudRibbon之後,SpringBoot會爲咱們自動化配置Ribbon,有些時候自動化配置是沒法知足須要的。咱們都知道在SpringBoot中咱們可使用兩種配置屬性的方法:使用java config方式和在配置文件中配置。
建立UserServiceConfig
,該類不能在啓動時候被掃描到,因此咱們須要將該類放到SpringBoot入口類的上一層路徑下。
@Configuration public class UserServiceConfig { /** *將服務檢查策略改成PingUrl * @return */ @Bean public IPing ribbonPing(){ return new PingUrl(); } /** * 將負載均衡的策略改成隨機選取服務實例 * @return */ @Bean public IRule ribbonRule(){ return new RandomRule(); } }
而後建立RibbonConfig
,這裏@RibbonClients
註解是能夠指定多個RibbonClient,而@RibbonClient
註解則是指定那個哪一個服務使用哪一個配置類
@Configuration @RibbonClients({ @RibbonClient(name = "user-service",configuration = UserServiceConfig.class), }) public class RibbonConfig { }
在配置文件中配置時候咱們也能夠配置全局的和指定客戶端方式配置
ribbon.<key>=<value>
,key客戶端配置參數名,value爲對應的參數值<client>.ribbon.<key>=<value>
,這裏的client爲指定的服務名。下面爲user-service指定負載均衡策略:USER-SERVICE: ribbon: RulePredicateClasses: com.netflix.loadbalancer.RandomRule
更多關於key的配置信息能夠查看com.netflix.client.config.CommonClientConfigKey
。
做爲SpringCloud學習筆記,可能有不少地方很差。望指出!!!
源碼地址:https://gitee.com/wqh3520/spring-cloud-1-9/tree/master/
原文地址:SpringCloud學習之Ribbon