您的位置:首页 > 编程语言 > Java开发

Spring Cloud 配置服务消费者和断路器

2017-01-06 17:24 459 查看
简单几步,配置spring-boot微服务消费者,以及相关的断路器(服务不可用时,调用该本地断路器输出相应的值)。假设该消费者需要调用一个叫做user的服务:
1、引入依赖(pom.xml):
<dependencies>
<!-- service discovery -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<!-- 其他依赖略。。。 -->
</dependencies>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Camden.SR3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>


2、配置文件配置(application.yml):
配置服务注册中心地址。消费者通过注册中心发现服务的具体地址。
eureka:
client:
register-with-eureka: false
service-url:
defaultZone: http://192.168.0.9:58000/eureka/,http://192.168.0.10:58000/eureka/,http://192.168.0.18:58000/eureka/


在网络情况差的地方,需要适当地改大超时时长的配置,以避免出现请求超时:
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 10000 # 请求超时时长,缺省为1000
threadpool:
default:
coreSize: 20 # 请求最大线程数,缺省为10

3、配置激活:
通过@EnableDiscoveryClient和@EnableFeignClients两个注解激活客户端:
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class AdminApplication {
public static void main(String[] args) {
SpringApplication.run(AdminApplication.class, args);
}
}


4、消费者(客户端)代码:
/**
* 调用user微服务的客户端接口
* @author XuJijun
*
*/
@FeignClient(value="user-service", fallback=UserServiceClientHystrix.class)
public interface UserServiceClient {

/**
* 根据userId获取电话号码
*/
@RequestMapping(value = "/user/getPhoneNoByUserId", method = RequestMethod.GET)
public String getPhoneNoByUserId(@RequestParam(value = "userId") Integer userId);
}


5、断路器代码:
/**
* UserServiceClient断路器:
* 当微服务不可用时,调用这个类的方法。
* @author XuJijun
*
*/
@Component
public class UserServiceClientHystrix implements UserServiceClient {

@Override
public String getPhoneNoByUserId(@RequestParam(value = "userId") Integer userId) {
return null;
}

}


6、测试:
@RunWith(SpringRunner.class)
@SpringBootTest//(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class AdminApplicationTests {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
UserServiceClient userServiceClient;

/**
* 微服务客户端测试
*/
@Test
public void userServiceClient() throws InterruptedException {
//由于网络和系统启动问题,需要推迟几秒钟才能从注册中心获取到服务信息
for(int i=0; i<5; i++) {
Thread.sleep(1000);
String phoneNo = userServiceClient.getPhoneNoByUserId(263508);
logger.debug("times: {}, phoneNo: {}", i+1, phoneNo);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息