Spring cloud整合consul、feign、hystrix

服務端:

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>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.5.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.snd</groupId>
	<artifactId>consul</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>consul</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
		<spring-cloud.version>Greenwich.SR1</spring-cloud.version>
	</properties>

	<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>
		
		<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-web</artifactId>
		</dependency>
		
	</dependencies>

	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>${spring-cloud.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

properties文件:

#項目名稱
spring.application.name=spring-cloud-consul-producer-one
#項目啓動端口
server.port=8501
#consul~IP
spring.cloud.consul.host=localhost
#consul~端口
spring.cloud.consul.port=8500
#註冊到consul的服務名稱
spring.cloud.consul.discovery.serviceName=consul-service-producer

controller測試:

package com.snd.consul.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
	
	@GetMapping("/hello")
	public String test() {
		System.out.println("TestController==>hello consul one");
		return "hello consul one";
	}

}

啓動類:

package com.snd.consul;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

/**
 * consul 服務端
 * @author Jobs
 *
 */
@SpringBootApplication
@EnableDiscoveryClient
public class ConsulApplication {

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

}

客戶端:

pom文件:

<?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>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.5.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.snd</groupId>
	<artifactId>consul-consumer</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>consul-consumer</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
		<spring-cloud.version>Greenwich.SR1</spring-cloud.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</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-consul-discovery</artifactId>
		</dependency>
		<!-- feign -->
		<dependency>
		  <groupId>org.springframework.cloud</groupId>
		  <artifactId>spring-cloud-starter-openfeign</artifactId>
		</dependency>
		
		<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
            <version>1.4.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
            <version>1.4.0.RELEASE</version>
        </dependency>
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>${spring-cloud.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

properties文件:

spring.application.name=spring-cloud-consul-consumer
server.port=8503
spring.cloud.consul.host=localhost
spring.cloud.consul.port=8500
#設置不需要註冊到 consul 中
spring.cloud.consul.discovery.register=false
#註冊到consul的服務名稱
#spring.cloud.consul.discovery.serviceName=consul-service-producer

#開啓熔斷機制
feign.hystrix.enabled=true

啓動類:

package com.snd.consul;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableFeignClients
@EnableCircuitBreaker
public class ConsulApplication {

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

}

controller層:

package com.snd.consul.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ServiceController {
	
	@Autowired
    private LoadBalancerClient loadBalancer;
    @Autowired
    private DiscoveryClient discoveryClient;
 
   /**
     * 獲取所有服務
     */
    @RequestMapping("/services")
    public Object services() {
        return discoveryClient.getInstances("consul-service-producer");
    }
 
    /**
     * 從所有服務中選擇一個服務(輪詢)
     */
    @RequestMapping("/discover")
    public Object discover() {
        return loadBalancer.choose("consul-service-producer").getUri().toString();
    }

}
package com.snd.consul.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.snd.consul.service.FeignClientService;

@RestController
public class TestController {

	 	@Autowired
	    private LoadBalancerClient loadBalancer;
	 	
	 	@Autowired
	 	private FeignClientService feignClientService;
	 
	    @RequestMapping("/call")
	    public String call() {
	        ServiceInstance serviceInstance = loadBalancer.choose("consul-service-producer");
	        System.out.println("服務地址:" + serviceInstance.getUri());
	        System.out.println("服務名稱:" + serviceInstance.getServiceId());
	        String callServiceResult = new RestTemplate().getForObject(serviceInstance.getUri().toString() + "/hello", String.class);
	        System.out.println(callServiceResult);
	        return callServiceResult;
	    }
	    
	    @GetMapping("/feign/test")
	    public String feign() {
	    	return feignClientService.testHello();
	    }
	    
	    @HystrixCommand(fallbackMethod="hystrixTest")
	    @GetMapping("/hystrix/test")
	    public String hystrix() {
	    	 System.out.println("/hystrix/test");
	    	 ServiceInstance serviceInstance = loadBalancer.choose("consul-service-producer");
		     String callServiceResult = new RestTemplate().getForObject(serviceInstance.getUri().toString() + "/hello", String.class);
		     return callServiceResult;
	    }
	    
	    public String hystrixTest() {
	    	return "調用服務發生錯誤,使用hystrix方法,非接口返回的值!";
	    }

}

service層:

package com.snd.consul.service;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

import com.snd.consul.service.impl.FallbackServiceImpl;

//@FeignClient("spring-cloud-consul-producer-two")
@FeignClient(value="consul-service-producer", fallback=FallbackServiceImpl.class)
public interface FeignClientService {
	
	@GetMapping("/hello")
	String testHello();

}
package com.snd.consul.service.impl;

import org.springframework.stereotype.Component;

import com.snd.consul.service.FeignClientService;

/**
 * 熔斷機制實現類
 * @author Jobs
 *
 */
@Component
public class FallbackServiceImpl implements FeignClientService {

	@Override
	public String testHello() {
		return "服務器熔斷-接口實現--返回值====1111!";
	}

}

步驟:

1、先在【https://www.consul.io/downloads.html】下載consul服務,然後解壓啓動。(window啓動:cd到consul解壓的目錄下執行:consul agent -dev)

2、啓動後打開網頁【http://localhost:8500/ui/dc1/services

3、更改服務端端口,啓動兩個服務端(爲了演示負載均衡【修改controller一些返回值和打印值,以方便知道是調用了哪個服務端】)

4、啓動客戶端服務執行:http://localhost:8503/serviceshttp://localhost:8503/callhttp://localhost:8503/feign/testhttp://localhost:8503/hystrix/test

5、斷開兩個服務端服務執行:http://localhost:8503/feign/testhttp://localhost:8503/hystrix/test發現熔斷機制已生效

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章