1. 程式人生 > >SpringCloud總結--SpringCloud簡單使用以及Ribbon和Feign的使用

SpringCloud總結--SpringCloud簡單使用以及Ribbon和Feign的使用

SpringCloud是基於SpringBoot的一整套實現微服務的框架。他提供了微服務開發所需的配置管理、服務發現、斷路器、智慧路由、微代理、控制匯流排、全域性鎖、決策競選、分散式會話和叢集狀態管理等元件。最重要的是,跟spring boot框架一起使用的話,會讓你開發微服務架構的雲服務非常好的方便。SpringCloud也是基於RPC遠端呼叫協議,所以也是需要一個註冊中心,註冊中心可以使用Eureka,zk(Zookeeper)等。

SpringCloud特點:

   1、SpringCloud 是基於SpringBoot的,所以擁有SpringBoot的所以特點
   2.約定優於配置
   3、開箱即用、快速啟用
   4、適用於各種環境
   5、輕量級的元件
   6、元件否支援很豐富,功能很齊全
   7、選型中立

下面就對SpringCloud的使用以及結合Ribbon的使用(註冊中心使用Eureka)

 

一、註冊中心Eureka的使用(這邊加入了Eureka的認證)

   a、pom.xml依賴

<parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.2.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <dependencies>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka-server</artifactId>
			<version>1.3.5.RELEASE</version>
		</dependency>
		
		<dependency>
		    <groupId>org.springframework.boot</groupId>
		    <artifactId>spring-boot-starter-security</artifactId>
		</dependency>
		
  </dependencies>

    b、application.yml

security:
  user:
    password: zj123
    name: user
  basic:
    enabled: true
server:
  port: 8761
eureka:
  client: 
    register-with-eureka: false
    fetch-registry: false
    defaultZone: http://user:[email protected]:8761/eureka

      eureka.client.register-with-eureka=false    ##當前Eureke只做服務,不作為客戶端,因為在高可用的環境下Eureka是服務也是客戶端,用於Eureka的同步
      eureka.client.fetch-registry=false          ##當前Eureke只做服務,不作為客戶端,因為在高可用的環境下Eureka是服務也是客戶端,用於Eureka的同步

c、啟動類

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class EurekaApplication {
  public static void main(String[] args) {
    SpringApplication.run(EurekaApplication.class, args);
  }
}

注:啟動後訪問http://localhost:8761 ,使用者名稱密碼:user,zj123(根據security的配置)

二、服務釋出者

1.pom.xml依賴(這邊添加了Mybaits的依賴)

<parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.2.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
  </parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
    <mybatis-spring-boot.version>1.2.0</mybatis-spring-boot.version>
    <mysql-connector.version>5.1.39</mysql-connector.version>
</properties>

<dependencies>
    <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>
		<version>1.3.5.RELEASE</version>
	</dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>${mybatis-spring-boot.version}</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>

2、application.yml

server:
  port: 8098
spring:
  application:
    name: provider-user
  datasource:
    url: jdbc:mysql://localhost:3306/spring-cloud
    username: root
    password: zj123456
    driver-class-name: com.mysql.jdbc.Driver
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.zhuojing.bean
eureka:
  client: 
    serviceUrl:
      defaultZone: http://user:[email protected]:8761/eureka
  instance:
    prefer-ip-address: true
    instance-id: ${spring.application.name}\:${spring.cloud.client.ipAddress}\:${spring.application.instance_id\:${server.port}}

3、Controller介面

@RestController
public class UserController {

	@Autowired
	private UserDao userDao;
	@GetMapping("/simple/{id}")
	public User getUserById(@PathVariable Long id){
		return userDao.getById(id);
	}
}

注:這邊dao使用Mybaits實現的就詳細說明,這邊介面就是根據請求引數請求一張表記錄

4、啟動類

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient
public class ApplocationTest {

	public static void main(String[] args) {
		SpringApplication.run(ApplocationTest.class, args);
	}

}

三、服務消費者使用(這邊使用Ribbon進行呼叫)

1、pom.xml的依賴

<parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.2.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
  </parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
    <mybatis-spring-boot.version>1.2.0</mybatis-spring-boot.version>
    <mysql-connector.version>5.1.39</mysql-connector.version>
</properties>

<dependencies>
    <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>
		<version>1.3.5.RELEASE</version>
	</dependency>
</dependencies>

2、application.yml

server:
  port: 8089
spring:
  application:
    name: customer-user
eureka:
  client: 
    serviceUrl: 
      defaultZone: http://user:[email protected]:8761/eureka
  instance:
    prefer-ip-address: true
    instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}
provider-user: 
  ribbon: 
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

3、呼叫:使用Ribbon呼叫

import java.util.Arrays;
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.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.zhuojing.bean.User;

@RestController
public class UserController {

	@Autowired
	private RestTemplate restTemplate;

	@GetMapping(value="/simple/{id}",produces=MediaType.APPLICATION_JSON_VALUE+";charset=utf-8")
	public User findUserById(@PathVariable Long id){
		//服務提供者地址  microservice-provider-user
		return this.restTemplate.getForObject("http://PROVIDER-USER/simple/"+id, User.class);
	}
	
}

4、啟動類

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableEurekaClient
public class AppCusRibbonPropertiesTest {

	@Bean
	@LoadBalanced
	public RestTemplate restTemplate(){
		return new RestTemplate();
	}
	public static void main(String[] args) {
		SpringApplication.run(AppCusRibbonPropertiesTest.class, args);
	}
}

使用Ribbon即時使用註解@LoadBalanced  使用即可

同時這邊使用基於配置檔案的方式配置了Ribbon的呼叫服務的負載策略:

provider-user: 
  ribbon: 
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

這邊使用的是隨機的方式,Ribbon還提供了多做負載均衡策略如輪詢,選擇最小併發等,同時還可以自定義負載均衡策略,這邊就不詳細介紹,剛興趣的可以自行查閱下資料

四、消費者的使用(使用Feign)

Feign是一個客戶端負載均衡的元件,預設負載均衡策略是輪詢

1、pom.xml 依賴

<parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.2.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
  </parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
    <mybatis-spring-boot.version>1.2.0</mybatis-spring-boot.version>
    <mysql-connector.version>5.1.39</mysql-connector.version>
</properties>

<dependencies>
    <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>
		<version>1.3.5.RELEASE</version>
	</dependency>
	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-feign</artifactId>
		<version>1.3.5.RELEASE</version>
	</dependency>
</dependencies>

2、application.yml

server:
  port: 8089
spring:
  application:
    name: customer-user
eureka:
  client: 
    serviceUrl: 
      defaultZone: http://user:[email protected]:8761/eureka
  instance:
    prefer-ip-address: true
    instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}

3、編寫feign介面,使用@FeignClient註解

import org.springframework.cloud.netflix.feign.FeignClient;

import com.config.Configuration1;
import com.zhuojing.bean.User;

import feign.Param;
import feign.RequestLine;

@FeignClient(name="provider-user",configuration=Configuration1.class)
public interface UserFeignClient {
  
	
	@RequestMapping(value = "/simple/{id}", method = RequestMethod.GET)
	public User getUserById(@PathVariable("id") Long id); 
// 兩個坑:1. @GetMapping不支援   2. @PathVariable得設定value
}

4、Controller呼叫類

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.zhuojing.bean.User;
import com.zhuojing.feign.UserFeignClient;

@RestController
public class UserController {

	@Autowired
	private UserFeignClient userFeignClient;

	@GetMapping(value="/simple/{id}",produces=MediaType.APPLICATION_JSON_VALUE+";charset=utf-8")
	public User findUserById(@PathVariable Long id){
		
		return userFeignClient.getUserById(id);
	}
}

4、啟動類

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class ApplicationCustomerFeignTest {

	public static void main(String[] args) {
		SpringApplication.run(ApplicationCustomerFeignTest.class, args);
	}
}

注:Feign使用是第一次可能會出現請求超時的問題,針對這個問題,有以下幾種角色方案

 # 解決第一次請求報超時異常的方案:
  hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 5000 
# 或者:
  hystrix.command.default.execution.timeout.enabled: false

# 或者:  
  feign.hystrix.enabled: false ## 索性禁用feign的hystrix支援

五、其他說明

服務消費者獲取List結果(坑,先轉化為陣列)
        @GetMapping("/getAllUser")
    public List<User> getAllUser(){
        User[] users = this.restTemplate.getForObject("http://provider-user/getAllUser", User[].class);
        List<User> list = Arrays.asList(users);
        for (User user : list) {
            System.out.println(user.getId());
        }
        return list;
    }