Skip to content

Commit cc978ec

Browse files
author
ZuRun's MacBook Pro
committed
RestTemplate的封装
1 parent 4c61984 commit cc978ec

10 files changed

Lines changed: 194 additions & 19 deletions

File tree

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# 基础模块
2+
3+
## 介绍
4+
5+
### RESTful
6+
7+
- RestConfig 实例化MyRestTemplate
8+
- 自定义MyRestTemplate
9+
- 自定义状态码相应策略

common/basis/pom.xml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,5 +11,11 @@
1111

1212
<artifactId>basis</artifactId>
1313

14+
<dependencies>
15+
<dependency>
16+
<groupId>org.springframework.cloud</groupId>
17+
<artifactId>spring-cloud-starter-ribbon</artifactId>
18+
</dependency>
19+
</dependencies>
1420

1521
</project>
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package me.zuhr.demo.basis.config;
2+
3+
import me.zuhr.demo.basis.restful.MyRestTemplate;
4+
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
5+
import org.springframework.context.annotation.Bean;
6+
import org.springframework.context.annotation.Configuration;
7+
8+
/**
9+
* @author zurun
10+
* @date 2018/2/25 00:07:28
11+
*/
12+
@Configuration
13+
public class RestConfig {
14+
15+
@Bean
16+
@LoadBalanced
17+
public MyRestTemplate myRestTemplate() {
18+
return new MyRestTemplate();
19+
}
20+
}
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
package me.zuhr.demo.basis.restful;
2+
3+
import org.springframework.http.HttpHeaders;
4+
import org.springframework.http.HttpStatus;
5+
import org.springframework.http.MediaType;
6+
import org.springframework.http.client.ClientHttpResponse;
7+
import org.springframework.util.FileCopyUtils;
8+
import org.springframework.web.client.ResponseErrorHandler;
9+
import org.springframework.web.client.UnknownHttpStatusCodeException;
10+
11+
import java.io.IOException;
12+
import java.nio.charset.Charset;
13+
14+
/**
15+
* 自定义状态码相应策略
16+
* RestTemplate默认对4和5开头的状态码 抛异常处理
17+
* 现在约定项目中微服务之间的通信,使用restful规范,对于非2开头的状态码统一处理
18+
* <p>
19+
* hasError()方法不变
20+
* handleError()中不做处理
21+
*
22+
* @author zurun
23+
* @date 2018/2/24 22:50:00
24+
*/
25+
public class MyResponseErrorHandler implements ResponseErrorHandler {
26+
27+
/**
28+
* 4开头和5开头的是请求错误的
29+
*
30+
* @param response
31+
* @return
32+
* @throws IOException
33+
* @see org.springframework.web.client.DefaultResponseErrorHandler#hasError(ClientHttpResponse)
34+
*/
35+
@Override
36+
public boolean hasError(ClientHttpResponse response) throws IOException {
37+
try {
38+
return hasError(getHttpStatusCode(response));
39+
} catch (UnknownHttpStatusCodeException ex) {
40+
return false;
41+
}
42+
}
43+
44+
45+
@Override
46+
public void handleError(ClientHttpResponse response) throws IOException {
47+
48+
}
49+
50+
/**
51+
* Template method called from {@link #hasError(ClientHttpResponse)}.
52+
* <p>The default implementation checks if the given status code is
53+
* {@link HttpStatus.Series#CLIENT_ERROR CLIENT_ERROR} or
54+
* {@link HttpStatus.Series#SERVER_ERROR SERVER_ERROR}.
55+
* Can be overridden in subclasses.
56+
*
57+
* @param statusCode the HTTP status code
58+
* @return {@code true} if the response has an error; {@code false} otherwise
59+
* @see #getHttpStatusCode(ClientHttpResponse)
60+
*/
61+
protected boolean hasError(HttpStatus statusCode) {
62+
return (statusCode.series() == HttpStatus.Series.CLIENT_ERROR ||
63+
statusCode.series() == HttpStatus.Series.SERVER_ERROR);
64+
}
65+
66+
protected HttpStatus getHttpStatusCode(ClientHttpResponse response) throws IOException {
67+
try {
68+
return response.getStatusCode();
69+
} catch (IllegalArgumentException ex) {
70+
throw new UnknownHttpStatusCodeException(response.getRawStatusCode(), response.getStatusText(),
71+
response.getHeaders(), getResponseBody(response), getCharset(response));
72+
}
73+
}
74+
75+
protected byte[] getResponseBody(ClientHttpResponse response) {
76+
try {
77+
return FileCopyUtils.copyToByteArray(response.getBody());
78+
} catch (IOException ex) {
79+
// ignore
80+
}
81+
return new byte[0];
82+
}
83+
84+
protected Charset getCharset(ClientHttpResponse response) {
85+
HttpHeaders headers = response.getHeaders();
86+
MediaType contentType = headers.getContentType();
87+
return (contentType != null ? contentType.getCharset() : null);
88+
}
89+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package me.zuhr.demo.basis.restful;
2+
3+
import org.springframework.web.client.RestTemplate;
4+
5+
/**
6+
* RESTful 设计规范下,根据实际情况对RestTemplate的封装
7+
*
8+
* @author zurun
9+
* @date 2018/2/24 17:42:56
10+
*/
11+
public class MyRestTemplate extends RestTemplate {
12+
13+
public MyRestTemplate() {
14+
// 自定义状态码相应策略
15+
this.setErrorHandler(new MyResponseErrorHandler());
16+
}
17+
18+
public <T> T post(String url) {
19+
// postForEntity();
20+
return null;
21+
}
22+
}

model-test/Eureka-Client-Service/src/main/java/me/zuhr/demo/ecs/action/HelloAction.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,9 @@ public class HelloAction {
1515
private int serverPort;
1616

1717
@RequestMapping(value = "/hello", method = RequestMethod.GET)
18-
public String hello() {
19-
return "Hello, Spring Cloud! My port is " + String.valueOf(serverPort);
18+
public String hello() throws Exception {
19+
throw new Exception("手动异常!");
20+
// return "Hello, Spring Cloud! My port is " + String.valueOf(serverPort);
2021
}
2122

2223
}

model-test/EurekaClientConsumer/pom.xml

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,11 @@
1616
<groupId>org.springframework.cloud</groupId>
1717
<artifactId>spring-cloud-starter-eureka</artifactId>
1818
</dependency>
19-
<dependency>
20-
<groupId>org.springframework.cloud</groupId>
21-
<artifactId>spring-cloud-starter-ribbon</artifactId>
22-
</dependency>
19+
<!--放在basis模块中-->
20+
<!--<dependency>-->
21+
<!--<groupId>org.springframework.cloud</groupId>-->
22+
<!--<artifactId>spring-cloud-starter-ribbon</artifactId>-->
23+
<!--</dependency>-->
2324

2425
<dependency>
2526
<groupId>me.zuhr</groupId>

model-test/EurekaClientConsumer/src/main/java/me/zuhr/demo/EurekaClientConsumerApplication.java

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,6 @@
33
import org.springframework.boot.SpringApplication;
44
import org.springframework.boot.autoconfigure.SpringBootApplication;
55
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
6-
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
7-
import org.springframework.context.annotation.Bean;
8-
import org.springframework.web.client.RestTemplate;
96

107
/**
118
* @author zurun
@@ -14,12 +11,12 @@
1411
@EnableDiscoveryClient
1512
@SpringBootApplication
1613
public class EurekaClientConsumerApplication {
17-
18-
@Bean
19-
@LoadBalanced
20-
RestTemplate restTemplate() {
21-
return new RestTemplate();
22-
}
14+
//
15+
// @Bean
16+
// @LoadBalanced
17+
// MyRestTemplate restTemplate() {
18+
// return new MyRestTemplate();
19+
// }
2320

2421
public static void main(String[] args) {
2522
SpringApplication.run(EurekaClientConsumerApplication.class, args);
Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
11
package me.zuhr.demo.ecc.action;
22

3-
import me.zuhr.demo.basis.enumration.ServiceNameEnum;
3+
import me.zuhr.demo.ecc.service.HelloService;
44
import org.springframework.beans.factory.annotation.Autowired;
55
import org.springframework.web.bind.annotation.RequestMapping;
66
import org.springframework.web.bind.annotation.RequestMethod;
77
import org.springframework.web.bind.annotation.RestController;
8-
import org.springframework.web.client.RestTemplate;
98

109
/**
1110
* @author zurun
@@ -14,11 +13,11 @@
1413
@RestController
1514
public class HelloAction {
1615
@Autowired
17-
private RestTemplate restTemplate;
16+
HelloService helloService;
1817

1918
@RequestMapping(value = "/hi", method = RequestMethod.GET)
2019
public String hello() {
21-
return restTemplate.getForEntity("http://"+ ServiceNameEnum.ECS.getValue()+"/hello", String.class).getBody();
20+
return helloService.test();
2221
}
2322

2423
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package me.zuhr.demo.ecc.service;
2+
3+
import me.zuhr.demo.basis.enumration.ServiceNameEnum;
4+
import me.zuhr.demo.basis.restful.MyRestTemplate;
5+
import org.springframework.beans.factory.annotation.Autowired;
6+
import org.springframework.http.HttpHeaders;
7+
import org.springframework.http.HttpStatus;
8+
import org.springframework.http.ResponseEntity;
9+
import org.springframework.stereotype.Service;
10+
11+
import java.util.Map;
12+
13+
/**
14+
* @author zurun
15+
* @date 2018/2/24 11:55:15
16+
*/
17+
@Service
18+
public class HelloService {
19+
@Autowired
20+
MyRestTemplate restTemplate;
21+
22+
public String test() {
23+
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://" + ServiceNameEnum.ECS.getValue() + "/hello", String.class);
24+
String body = responseEntity.getBody();
25+
HttpStatus httpStatus = responseEntity.getStatusCode();
26+
int statusCode = responseEntity.getStatusCodeValue();
27+
HttpHeaders httpHeaders = responseEntity.getHeaders();
28+
Map<String, String> map = responseEntity.getHeaders().toSingleValueMap();
29+
return body;
30+
}
31+
}

0 commit comments

Comments
 (0)