提交 | 用户 | 时间
|
e7c126
|
1 |
package com.iailab.framework.env.core.util; |
H |
2 |
|
|
3 |
import com.iailab.framework.env.config.EnvProperties; |
|
4 |
import feign.RequestTemplate; |
|
5 |
import lombok.SneakyThrows; |
|
6 |
import org.springframework.cloud.client.ServiceInstance; |
|
7 |
import org.springframework.core.env.Environment; |
|
8 |
|
|
9 |
import javax.servlet.http.HttpServletRequest; |
|
10 |
import java.net.InetAddress; |
|
11 |
import java.util.Objects; |
|
12 |
|
|
13 |
/** |
|
14 |
* 环境 Utils |
|
15 |
* |
|
16 |
* @author iailab |
|
17 |
*/ |
|
18 |
public class EnvUtils { |
|
19 |
|
|
20 |
private static final String HEADER_TAG = "tag"; |
|
21 |
|
|
22 |
public static final String HOST_NAME_VALUE = "${HOSTNAME}"; |
|
23 |
|
|
24 |
public static String getTag(HttpServletRequest request) { |
|
25 |
String tag = request.getHeader(HEADER_TAG); |
|
26 |
// 如果请求的是 "${HOSTNAME}",则解析成对应的本地主机名 |
|
27 |
// 目的:特殊逻辑,解决 IDEA Rest Client 不支持环境变量的读取,所以就服务器来做 |
|
28 |
return Objects.equals(tag, HOST_NAME_VALUE) ? getHostName() : tag; |
|
29 |
} |
|
30 |
|
|
31 |
public static String getTag(ServiceInstance instance) { |
|
32 |
return instance.getMetadata().get(HEADER_TAG); |
|
33 |
} |
|
34 |
|
|
35 |
public static String getTag(Environment environment) { |
|
36 |
String tag = environment.getProperty(EnvProperties.TAG_KEY); |
|
37 |
// 如果请求的是 "${HOSTNAME}",则解析成对应的本地主机名 |
|
38 |
// 目的:特殊逻辑,解决 IDEA Rest Client 不支持环境变量的读取,所以就服务器来做 |
|
39 |
return Objects.equals(tag, HOST_NAME_VALUE) ? getHostName() : tag; |
|
40 |
} |
|
41 |
|
|
42 |
public static void setTag(RequestTemplate requestTemplate, String tag) { |
|
43 |
requestTemplate.header(HEADER_TAG, tag); |
|
44 |
} |
|
45 |
|
|
46 |
/** |
|
47 |
* 获得 hostname 主机名 |
|
48 |
* |
|
49 |
* @return 主机名 |
|
50 |
*/ |
|
51 |
@SneakyThrows |
|
52 |
public static String getHostName() { |
|
53 |
return InetAddress.getLocalHost().getHostName(); |
|
54 |
} |
|
55 |
|
|
56 |
} |