1.导入hystrix的依赖
<!--hystrix-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
2.在主程序上使用注解标识为hystrix
@EnableCircuitBreaker
3.在指定的服务调用上使用注解@HystrixCommand指定断路方法
package com.ooyhao.cloud.serverrole.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.ooyhao.cloud.serverrole.bean.Role;
import com.ooyhao.cloud.serverrole.bean.User;
import com.ooyhao.cloud.serverrole.mapper.RoleMapper;
import com.ooyhao.cloud.serverrole.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.List;
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper,Role> implements RoleService {
@Autowired
private RoleMapper roleMapper;
@Autowired
private RestTemplate restTemplate;
public List<Role> findRolesByUserId(Integer id){
return roleMapper.findRolesByUserId(id);
}
@HystrixCommand(fallbackMethod = "findUsersFallBack")
public List<User> findUsersByRoleId(Integer id){
List<User> user = restTemplate.getForObject(
"http://SERVER-USER/user/findUsersByRoleId/{id}",
List.class,
id);
return user;
}
public List<User> findUsersFallBack(Integer id) {
System.out.println("id:" + id);
List<User> users = new ArrayList<>();
User user = new User();
user.setUsername("oooooo");
user.setPassword("pppppp");
users.add(user);
return users;
}
}