问题场景:在学习springcloud config动态配置时,使用@Value("${version}"),发现取到的version=null
代码:
@RestController
public class CustomerController {
@Value("${version}")
private String version;
@GetMapping ("/version")
private String version ()
{
return version;//发送请求返回结果为null
}
配置文件
spring:
profiles:
active:
- dev
---
spring:
profiles: dev #开发环境
application:
name: Customer-dev
version: v-dev
---
spring:
profiles: test #测试环境
application:
name: Customer-test
version: v-test
# 请保存为UTF-8格式
通过排查发现在CustomerController.customerFeignClient方法使用的@HystrixCommand注解,导致version值为null,注释该注解后version值能正常注入
代码:
package moon.controller;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import moon.client.SearchClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class CustomerController {
@Autowired
private RestTemplate restTemplate;
//@HystrixCommand 影响 @Value注入值
@Value("${version}")
private String version;
@Autowired
private SearchClient searchClient;
@GetMapping ("/version")
private String version ()
{
return version;
}
@GetMapping("/customer")
public String customer ()
{
// //创建Search模块,并注册到Eureka
// InstanceInfo search = eurekaClient.getNextServerFromEureka("Search", false);
// //使用InstanceInfo,获取url
// String homePageUrl = search.getHomePageUrl();
// System.out.println(homePageUrl);
//使用RestTemplate调用
String result = restTemplate.getForObject("http://Search/search", String.class);
return result;
}
//降级隔离:当customerFeignClient方法报错时,去执行一个降级方法,返回托底数据
@GetMapping("/customerFeignClient")
//fallbackMethod 托底方法
//线程隔离策略
// @HystrixCommand (fallbackMethod = "customerFeignClientFallBack", commandProperties = {
// @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),//请求阈值
// @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "70"),//请求失败百分比达到阈值时,则打开断路器
// @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),//断路器是否启动
// @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "5000"),//断路器打开后,过多少秒后变为半开的状态
// @HystrixProperty(name = "circuitBreaker.forceOpen", value = "true")//断路器打开,拒绝请求
// })
public String customerFeignClient (@RequestParam("id") Integer id)
{
System.out.println(Thread.currentThread().getName());
if (id == 1)
{
int a = 1 / 0;
}
String result = searchClient.search();
return result;
}
//降级隔离:托底方法
@ResponseBody
public String customerFeignClientFallBack (@RequestParam("id") Integer id)
{
System.out.println("托底方法");
return "default";
}
}