溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Spring Cloud如何整合Hystrix

發(fā)布時間:2021-12-24 10:26:00 來源:億速云 閱讀:159 作者:小新 欄目:云計算

這篇文章給大家分享的是有關(guān)Spring Cloud如何整合Hystrix的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

19 Spring Cloud整合Hystrix

        Hystrix主要用于保護調(diào)用服務(wù)的一方,如果被調(diào)用的服務(wù)發(fā)生故障,符合一定條件,就開啟斷路器,對調(diào)用的程序進行隔離。在開始講述本章的內(nèi)容前,先準備測試項目,本章例子所使用的項目如下:

  • spring-hystrix-server:Eureka服務(wù)器,端口為8761,代碼目錄codes\06\6.4\spring-hystrix-server。

  • spring-hystrix-provider:服務(wù)提供者,本例只需要啟動一個實例,端口為8080,默認提供“/person/{personId}”服務(wù),根據(jù)personId參數(shù)返回一個Person實例,另外再提供一個“/hello”服務(wù),返回普通的字符串。代碼目錄為codes\06\6.4\spring-hystrix-provider

  • spring-hystrix-invoker:服務(wù)調(diào)用者,9000端口,代碼目錄codes\06\6.4\spring-hystrix-invoker。

整合Hystrix

        為服務(wù)調(diào)用者(spring-hystrix-invoker)項目添加依賴,添加后的依賴如下:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<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-hystrix</artifactId>
</dependency>

        在服務(wù)調(diào)用者的應(yīng)用啟動類中,加入啟用斷路器的注解,請見以下代碼片斷:

@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
public class InvokerApplication {

    @LoadBalanced
    @Bean
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }

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

        新建服務(wù)類,在服務(wù)方法中調(diào)用服務(wù),請見代碼清單6-17。

        代碼清單6-17:

        codes\06\6.4\spring-hystrix-invoker\src\main\java\org\crazyit\cloud\PersonService.java

@Component
public class PersonService {

	@Autowired
	private RestTemplate restTemplate;

	@HystrixCommand(fallbackMethod = "getPersonFallback")
	public Person getPerson(Integer id) {
		// 使用RestTemplate調(diào)用Eureka服務(wù)
		Person p = restTemplate.getForObject(
				"http://spring-hystrix-provider/person/{personId}",
				Person.class, id);
		return p;
	}

	/**
	 * 回退方法,返回一個默認的Person
	 */
	public Person getPersonFallback(Integer id) {
		Person p = new Person();
		p.setId(0);
		p.setName("Crazyit");
		p.setAge(-1);
		p.setMessage("request error");
		return p;
	}
}

        服務(wù)類中注入了RestTemplate,服務(wù)方法使用了@HystrixCommand注解進行修飾,并且配置了回退方法。@HystrixCommand注解由Hystrix的“javanica”項目提供,該項目主要是為了簡化Hystrix的使用。被@HystrixCommand修飾的方法,Hystrix(javanica)會使用AspectJ對其進行代理,Spring會將相關(guān)的類轉(zhuǎn)換為Bean放到容器中,在Spring Cloud中,我們無需過多關(guān)心Hystrix的命令管理。

        接下來,編寫控制器,調(diào)用服務(wù)類的方法,請見代碼清單6-18。

        代碼清單6-18:

        codes\06\6.4\spring-hystrix-invoker\src\main\java\org\crazyit\cloud\InvokerController.java

@RestController
@Configuration
public class InvokerController {

	@Autowired
	private PersonService personService;

	@RequestMapping(value = "/router/{personId}", method = RequestMethod.GET, 
			produces = MediaType.APPLICATION_JSON_VALUE)
	public Person router(@PathVariable Integer personId) {
		Person p = personService.getPerson(personId);
		return p;
	}
}

        控制器實現(xiàn)較為簡單,直接注入PersonService,調(diào)用方法即可,按以下步驟啟動集群:

  •  啟動“spring-hystrix-server”,本例中配置端口為8761。

  •  啟動“spring-hystrix-provider”,啟動一個實例,端口為8080。

  • 啟動“spring-hystrix-invoker”,端口為9000。

        打開瀏覽器訪問:http://localhost:9000/router/1,輸出如下:

{"id":1,"name":"Crazyit","age":33,"message":"http://localhost:8080/person/1"}

        停止服務(wù)提供者(spring-hystrix-provide),即停止8080端口,再訪問9000端口的地址,輸出如下:

{"id":0,"name":"Crazyit","age":-1,"message":"request error"}

        根據(jù)輸出可知,由于調(diào)用失敗,觸發(fā)了回退方法。

命令配置

        Spring Cloud中使用@HystrixCommand來聲明一個命令,命令的相關(guān)配置,也可以在該注解中進行,以下的代碼片斷,配置了幾個屬性:

	/**
	 * 測試配置,對3個key進行命名
	 * 設(shè)置命令執(zhí)行超時時間為1000毫秒
	 * 設(shè)置命令執(zhí)行的線程池大小為1
	 */
	@HystrixCommand(
			fallbackMethod="testConfigFallback", groupKey="MyGroup", 
			commandKey="MyCommandKey", threadPoolKey="MyCommandPool", 
			commandProperties={
					@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", 
							value = "1000")
			}, 
			threadPoolProperties={
					@HystrixProperty(name = "coreSize", 
							value = "1")
			})

        除了以上的幾個配置外,@HystrixCommand注解還可以使用ignoreExceptions來處理異常的傳播,請見以下代碼片斷:

	/**
	 * 聲明了忽略MyException,如果方法拋出MyException,則不會觸發(fā)回退
	 */
	@HystrixCommand(ignoreExceptions = {MyException.class}, 
			fallbackMethod="testExceptionFallBack")
	public String testException() {
		throw new MyException();
	}

        Hystrix的命令、線程配置較多,由于篇幅所限,本小節(jié)僅簡單地列舉幾個,讀者可舉一反三,按需要進行配置。

默認配置

        對于一些默認的配置,例如命令組的key等,可以使用@DefaultProperties注解,這樣就減少了@HystrixCommand注解的代碼量。以下代碼片斷展示如何使用@DefaultProperties:

@DefaultProperties(groupKey="GroupPersonKey")
public class PersonService {
	
	@HystrixCommand // group key將使用“GroupPersonKey”
	public String hello() {
		return "";
	}
}

        除了定義GroupKey外,還支持@HystrixCommand的其余配置,例如線程屬性、命令屬性等。

感謝各位的閱讀!關(guān)于“Spring Cloud如何整合Hystrix”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI