Web/SpringBoot

[spring] RestTemplate 클라이언트 사용법, 동적으로 header 추가

벨포트조던 2020. 1. 6.
반응형

spring에서 rest api 클라이언트를 사용해야해서 

 

조건

jersey와 restTemplate 중 뭘 쓸지 고민함.

https://code-examples.net/ko/q/11b5bde

- 간략한 비교글

 

비교했을때, 뭐 단순비교는 안되고, 작동방식이 다른거같음. 

아는분 말로는 3~4년전에 비교했을때 jersey가 빨랏다고는 함. 확실치 않으니 참고만 하자 

 

jersey 사용을 좀 했으니 잘 안써보고, 지금 적용하기가 resttemplate이 나은것같아 사용하기로함. 

 

 

요약

- restTemplate 은 200 이 아니면 exception을 던진다 ( exchange 로 호출 시 ) 

 

-동적으로 resttemplate Header값 추가하기 

https://stackoverflow.com/questions/19238715/how-to-set-an-accept-header-on-spring-resttemplate-request/19239013

 

=====내 코드 =====

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
 
@Component
public class ScheduledTasks {
 
    private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);
 
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
 
    @Autowired
    private KafkaTemplate kafkaTemplate;
    
    @Autowired
    @Qualifier("syncHwPermissionClient")
    MongoClient permissionMongo;
 
    // -stg으로 바꾸면 안됨 -> 바꾸면  stg에 남아있던 lag이 전부 실행됨.. 
    @KafkaListener(topics = "sync-data-bill", groupId = "sync-data-bill-consumer")
    public void receiveTopic1(ConsumerRecord consumerRecord, Acknowledgment acknowledgment) {
        
        JsonParser parser = new JsonParser();
        JsonObject json = (JsonObject) parser.parse(consumerRecord.value().toString());
        
        String method = json.get("method").getAsString();
        String url = json.get("url").getAsString();
        JsonArray header = json.getAsJsonArray("header");
//        JsonObject payload = json.getAsJsonArray("payload").get(0).getAsJsonObject();
        JsonArray payload = json.getAsJsonArray("payload");
        
        
        HttpMethod httpmethod = null;
        switch (method) {
            case "GET":
                httpmethod = HttpMethod.GET;
                break;
            case "POST":
                httpmethod = HttpMethod.POST;
                break;
            case "PUT":
                httpmethod = HttpMethod.PUT;
                break;
            case "DELETE":
                httpmethod = HttpMethod.DELETE;
                break;
            default:
                break;
        }
        
        
        List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
        
        if (header != null) {
            for (JsonElement arr : header) {
                JsonObject jsonObject = arr.getAsJsonObject();
                
                List<String> keys = jsonObject.entrySet()
                        .stream()
                        .map(i -> i.getKey())
                        .collect(Collectors.toCollection(ArrayList::new));
                
                keys.forEach(i -> {
                    interceptors.add(new HeaderRequestInterceptor(i, jsonObject.get(i).getAsString() ));
                });
            }
        }
        
        
        HttpHeaders headers = new HttpHeaders();
        String bodystring = "";
        if (payload != null
            bodystring = payload.get(0).getAsJsonObject().toString();
        
        HttpEntity<String> entity = new HttpEntity<String>(bodystring);
        
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setInterceptors(interceptors);
        ResponseEntity<String> result = null;
        
        try {
            result = restTemplate.exchange(URI.create(url), httpmethod, entity, String.class);
            
            if (result.getStatusCodeValue() == 200 ) {
                acknowledgment.acknowledge();
            }else {
                log.error("[ERROR] consumer statuscode not 200 - "+ result + " consumber data - " + consumerRecord.toString() );
            }
            
        }catch(HttpClientErrorException  exception) {
            String result_ex = exception.getResponseBodyAsString();
            log.error("[ERROR] consumer HttpClientErrorException- "+ result_ex + " consumber data - " + consumerRecord.toString() );
            // 실패시 retry 입력
 
            throw exception;
        }catch (Exception e) {
            // TODO: handle exception
              log.error("[ERROR] consumer Exception - " + e + " consumber data - " + consumerRecord.toString() );
              throw e;
        }
       
    }
    
    public class HeaderRequestInterceptor implements ClientHttpRequestInterceptor {
 
        private final String headerName;
 
        private final String headerValue;
 
        public HeaderRequestInterceptor(String headerName, String headerValue) {
            this.headerName = headerName;
            this.headerValue = headerValue;
        }
 
        @Override
        public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
            request.getHeaders().set(headerName, headerValue);
            return execution.execute(request, body);
        }
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

 

-------------------- 참고

 - Resttemplate 으로 client 호출하는 기본 샘플 ( pojo 참고할 만함 )

https://jsonobject.tistory.com/237 

 - 기본 샘플

https://springbootdev.com/2017/11/21/spring-resttemplate-exchange-method/

- SPRING-Spring-Resttemplate-예외-처리

https://cnpnote.tistory.com/entry/SPRING-Spring-Resttemplate-%EC%98%88%EC%99%B8-%EC%B2%98%EB%A6%AC

- SPRING-Spring-RestTemplate-요청에-Accept-헤더를-설정하는-방법

https://cnpnote.tistory.com/entry/SPRING-Spring-RestTemplate-%EC%9A%94%EC%B2%AD%EC%97%90-Accept-%ED%97%A4%EB%8D%94%EB%A5%BC-%EC%84%A4%EC%A0%95%ED%95%98%EB%8A%94-%EB%B0%A9%EB%B2%95

 

반응형

댓글