代码结构如下:
pom 文件中添加 hystrix
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</artifactId> </dependency>
UserApplication 添加 @EnableHystrix 代码如下
package com.study.user; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.netflix.feign.EnableFeignClients; import org.springframework.cloud.netflix.hystrix.EnableHystrix; @EnableEurekaClient @SpringBootApplication @EnableHystrix public class UserApplication { public static void main(String[] args) { SpringApplication.run(UserApplication.class, args); } }
UserService 代码如下
package com.study.user.service; import java.util.List; import java.util.Map; public interface UserService { List<Map<String, Object>> getMenu(); }
UserServiceImpl 代码如下
package com.study.user.service.impl; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import com.study.user.service.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Service public class UserServiceImpl implements UserService { private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class); @Autowired private LoadBalancerClient loadBalancerClient;//ribbon负载均衡器s public List<Map<String, Object>> getMenuError() { List<Map<String, Object>> list = new ArrayList<>(); Map<String, Object> map = new HashMap<>(); map.put("menu", "菜单1111122222"); list.add(map); return list; } @HystrixCommand(fallbackMethod = "getMenuError") @Override public List<Map<String, Object>> getMenu() { //选择调用的服务的名称 //ServiceInstance 封装了服务的基本信息,如 IP,端口 ServiceInstance si = this.loadBalancerClient.choose("menu"); //拼接访问服务的URL StringBuffer sb = new StringBuffer(); //http://localhost:9090/user sb.append("http://").append(si.getHost()).append(":").append(si.getPort()).append("/menu/getMenu"); //springMVC RestTemplate RestTemplate rt = new RestTemplate(); ParameterizedTypeReference<List<Map<String, Object>>> type = new ParameterizedTypeReference<List<Map<String, Object>>>() { }; //ResponseEntity:封装了返回值信息 ResponseEntity<List<Map<String, Object>>> response = rt.exchange(sb.toString(), HttpMethod.GET, null, type); List<Map<String, Object>> list = response.getBody(); return list; } }
代码结束
访问 http://127.0.0.1:8763/user/getMenu
扫描二维码关注公众号,回复:
4464011 查看本文章