引入restTemplate
@EnableDiscoveryClient
@EnableFeignClients
@SpringBootApplication
public class OrderApplication {
@Bean
@LoadBalanced
//添加注解@SentinelRestTemplate
@SentinelRestTemplate
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class);
}
}
控制器,通过RestTemplate 实现http请求
@RestController
public class RestTemplateController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/order/{id}")
public String getUser(@PathVariable Integer id){
String result = restTemplate.getForObject("http://msb-user:10001/user/" + id, String.class);
return result;
}
}
服务提供者
@RestController
public class UserController {
@GetMapping("/user/{userId}")
public String getUserName(@PathVariable Integer userId){
return "善缘老师";
}
}
添加流控
注意选对流控请求
正常请求
频繁请求
统一异常处理
注解添加属性
@Bean
@LoadBalanced
@SentinelRestTemplate(blockHandler = "handleException",
blockHandlerClass= GlobalException.class
,fallback = "fallback",
fallbackClass = GlobalException.class)
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class);
}
异常类注意对象的引用,引用错误则启动报错
import com.alibaba.cloud.sentinel.rest.SentinelClientHttpResponse;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.msb.order.util.Result;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
public class GlobalException {
public static SentinelClientHttpResponse handleException(HttpRequest request,
byte[] body, ClientHttpRequestExecution execution, BlockException ex) {
Result r = Result.error(-1, "===被限流啦===");
System.out.println("近日来零三零三零是否");
try {
return new SentinelClientHttpResponse(new ObjectMapper().writeValueAsString(r));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
public static SentinelClientHttpResponse fallback(HttpRequest request,
byte[] body, ClientHttpRequestExecution execution, BlockException ex) {
Result r = Result.error(-2, "===被异常降级啦===");
System.out.println("近日来零三零三零是否2");
try {
return new SentinelClientHttpResponse(new ObjectMapper().writeValueAsString(r));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}
异常请求