php熔断机制,springcloud熔断机制(示例代码)

熔断机制,指的是微服务架构中,由于某个服务瘫痪,为避免影响整个系统而采取的降级服务

简述:

由于网络或自身原因,服务不能确保一定可用。如果某个服务出现了问题,调用方的大量请求会使Servlet容器的线程资源被耗尽,导致服务瘫痪。而且这种故障会传播,进而威胁到这个微服务系统可用性

示例如下:基于springboot1.5.10

添加依赖:

org.springframework.boot

spring-boot-starter-web

1.5.10.RELEASE

org.springframework.cloud

spring-cloud-starter-netflix-eureka-client

1.4.3.RELEASE

org.springframework.cloud

spring-cloud-starter-netflix-hystrix

1.4.3.RELEASE

application配置

server:

port: 8901 #程序启动端口,也是Tomcat端口

spring:

application:

name: customer-order-hystrix #应用别名

eureka:

client:

service-url:

defaultZone: http://user:123@localhost:10000/eureka

instance:

instance-id: ${spring.cloud.client.ipAddress}:${spring.application.name}:${spring.application.instance_id:${server.port}}

prefer-ip-address: true

启动类

@SpringBootApplication

@EnableEurekaClient

@EnableCircuitBreaker //启用熔断

public class CustomerHystrixApplication

{

@Bean

public RestTemplate getTemp(){

return new RestTemplate();

}

public static void main( String[] args )

{

SpringApplication.run(CustomerHystrixApplication.class,args);

System.out.println("customer start-up success");

}

}

实体类

public class User {

private Long id;

private Date date;

public User() {

}

public User(Long id) {

this.id = id;

this.date = new Date();

}

public void setId(Long id) {

this.id = id;

}

public void setDate(Date date) {

this.date = date;

}

public Long getId() {

return id;

}

public Date getDate() {

return date;

}

Controller

@RestController

public class CustomeController {

@Autowired

private EurekaClient eurekaClient;

@Autowired

private RestTemplate restTemplate;//springboot提供的用于访问rest接口的对象

@GetMapping("/order/{id}")

@HystrixCommand(fallbackMethod = "errora1")

public User getOrder(@PathVariable Long id){

InstanceInfo instanceInfo = eurekaClient.getNextServerFromEureka("provider-user", false);

String homePageUrl = instanceInfo.getHomePageUrl();

// 访问提供者,获取数据

User user = restTemplate.getForObject(homePageUrl+"/user/" + id,User.class);//通过访问rest获取json数据,然后转换成user对象

return user;

}

/**

* 失败后执行的回调函数

* @param id

* @return

*/

public User errora1(Long id) {

User user = new User();

user.setId(-1000L);

user.setDate(new Date());

return user;

}

}

注:回调函数和其使用者应返回相同的类型,这里省略了服务提供者模块 provider-user

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值