Hystrix
@HystrixCommand
1.故障隔離 註解方式
Hystrix我常用到的功能是故障隔離,做爲一個熔斷組件,在依賴服務調用出錯的時候,我們可以@HystrixCommand(fallbackMethod = "")來指定調用失敗後調的方法,而不是一直阻塞
2.故障隔離 代碼方式
Hystrix有一個抽象類,HystrixCommend抽象類,我們可以繼承這個類,然後重寫getFallback()來實現故障隔離
import org.springframework.web.client.RestTemplate;
import com.netflix.hystrix.HystrixCommand;
import com.superlighting.domain.User;
public class UserCommand extends HystrixCommand<User>{
User u;
RestTemplate restTemplate;
protected UserCommand(Setter setter,RestTemplate restTemplate,User u) {
super(setter);
this.u = u;
this.restTemplate = restTemplate;
}
@Override
protected User run() throws Exception {
return restTemplate.postForObject("http://user-service/login", u, User.class);
}
@Override
protected User getFallback(){
return new User();
}
}
3.異常處理
如果我們調用依賴服務的時候,我們知道可能會發生一些異常,而這些異常發生時我們不希望會觸發服務降級的fallback(),這個時候我們可以使用@HystrixCommand(ignoreExceptions = {BadRequesException.class}),當BadRequesException異常發生時,我們忽略此異常,不走fallback().
4.異常獲取
當發生一些異常,走了我們的fallback()方法時,我們想要獲取異常信息,來做一些處理,這個時候我們可以在回調方法裏面處理異常。
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestTemplate;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.superlighting.domain.User;
@Service
public class HelloService {
//負載均衡
@Autowired
private RestTemplate restTemplate;
@HystrixCommand(fallbackMethod="hiError")//這個服務崩潰之後,會走HystrixCommand括號裏面的方法
public User hiS(@RequestBody User u){
System.out.println(u.getUserName());
System.out.println(u.getPassword());
return restTemplate.postForObject("http://user-service/login", u, User.class);
//return restTemplate.getForObject("http://user-service/login", String.class);
}
public User hiError(@RequestBody User u, Throwable e){
System.out.println(e.getMessage());
return new User();
}
public static void main(String[] args) {
Map<String,String> map = new HashMap<>();
map.put("1","1");
System.out.println("1".hashCode());
}
}
4.請求緩存
我們調用一些依賴服務獲取信息的時候,可以加入緩存,來提升返回的速度(這個表達不是很準確)
@CacheResult //加入這個註解說明開啓了緩存,同時我們還可以在請求參數上面加上
//@CacheKey註解來定義緩存key,如果傳入的緩存key相同,則返回緩存裏面的內容
@HystrixCommand(fallbackMethod="hiError")//這個服務崩潰之後,
//會走HystrixCommand括號裏面的方法
public User hiS(@RequestBody @CacheKey("id") User u){
System.out.println(u.getUserName());
System.out.println(u.getPassword());
return restTemplate.postForObject("http://user-service/login", u, User.class);
//return restTemplate.getForObject("http://user-service/login", String.class);
}
5.緩存清理
如果依賴服務後面的邏輯改變,加入了update操作的話,我們再使用緩存裏面的數據可能不準確,有時候我們需要清理緩存
//清除方法hiS的緩存
@CacheRemove(commandKey = "hiS")
public User hiError(@RequestBody User u, Throwable e){
System.out.println(e.getMessage());
return new User();
}
6.請求合併