@Service
public class PaymentService {
@HystrixCommand(fallbackMethod ="handOk",commandProperties ={
@HystrixProperty(name ="execution.isolation.thread.timeoutInMilliseconds",value ="1500")})
public String paymentInfo_Ok(Integer id){int i =10/0;return"线程池:"+ Thread.currentThread().getName()+" ,paymentInfo_OK,id:"+ id;}
超时访问的方法
@HystrixCommand(fallbackMethod ="handTimeOut",commandProperties ={
@HystrixProperty(name ="execution.isolation.thread.timeoutInMilliseconds",value ="3000")})
public String paymentInfo_Timeout(Integer id){int interTime =3;//int i = 10/0;
try{
TimeUnit.SECONDS.sleep(interTime);}catch (Exception e){
e.printStackTrace();}return"线程池:"+ Thread.currentThread().getName()+" ,paymentInfo_Timeout,id:"+ id +"耗时"+ interTime +"秒钟";return"hello";}
public String handTimeOut(Integer id){return"调用服务超时,请稍后再试!";}
public String handOk(Integer id){return"服务器内部资源错误,请稍后再试!";}
3)、在启动类上开启服务熔断的功能 @SpringCloudApplication
//@SpringBootApplication//@EnableDiscoveryClient//@EnableCircuitBreaker//这个注解包含上面三个注解
@SpringCloudApplication
public class HystrixPaymentApplication {
public staticvoidmain(String[] args){
SpringApplication.run(HystrixPaymentApplication.class,args);}
4)、将降级的逻辑应用在某个服务上
@HystrixCommand(fallbackMethod="降级逻辑的方法名",commandProperties={
@HystrixProperties(name ="execution.isolation.thread.timeoutInMilliseconds",value ="1500")})
public String timeout(){}
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableCircuitBreaker//开启熔断器
public class HystrixOrderApplication {
public staticvoidmain(String[] args){
SpringApplication.run(HystrixOrderApplication.class,args);}}
2)、在消费方的controller里面,定义一个全局降级的方法。
//全局降级处理方法
public String globalHandler(){return"这是全局处理降级逻辑的方法.......";}
@Component
public class FallBackService implements OrderHystrixClient {
@Override
public String ok(Integer id){return"进行paymentInfo_OK方法降级处理......";}
@Override
public String timeout(Integer id){return"进行paymentInfo_Timeout方法降级处理";}}
3)、修改Feign客户端接口
@Component
public class FallBackService implements OrderHystrixClient {
@Override
public String ok(Integer id){return"进行paymentInfo_OK方法降级处理......";}
@Override
public String timeout(Integer id){return"进行paymentInfo_Timeout方法降级处理";}}
分布式服务架构、微服务架构与 API 网关
在微服务架构里,服务的粒度被进一步细分,各个业务服务可以被独立的设计、开发、测试、部署和管理。
这时,各个独立部署单元可以用不同的开发测试团队维护,可以使用不同的编程语言和技术平台进行设计,
这就要求必须使用一种语言和平 台无关的服务协议作为各个单元间的通讯方式。
2)、API 网关的定义
网关的角色是作为一个 API 架构,用来保护、增强和控制对于 API 服务的访问。
API 网关是一个处于应用程序或服务(提供 REST API 接口服务)之前的系统,用来管理授权、
访问控制和流量限制等,这样 REST API 接口服务就被 API 网关保护起来,对所有的调用者透明。
因此,隐藏在 API 网关后面的业务系统就可以专注于创建和管理服务,而不用去处理这些策略性的基础设施。
3)、Gateway是什么
Spring Cloud Gateway是Spring官方基于Spring 5.0,Spring Boot 2.0和Project Reactor等技术开发的网关,
Spring Cloud Gateway旨在为微服务架构提供一种简单而有效的统一的API路由管理方式。
Spring Cloud Gateway作为Spring Cloud生态系中的网关,目标是替代ZUUL,其不仅提供统一的路由方式,
并且基于Filter链的方式提供了网关基本的功能,例如:安全,监控/埋点,和限流等。
@SpringBootApplication
@EnableEurekaClient
public class GatewayMain9527 {
public staticvoidmain(String[] args){
SpringApplication.run(GatewayMain9527.class,args);}}