什么是resttemplate
傳統情況下在java代碼里訪問restful服務,一般使用apache的httpclient。不過此種方法使用起來太過繁瑣。spring提供了一種簡單便捷的模板類來進行操作,這就是resttemplate。
準備
服務端我是用的是一個普通的api
1
2
3
4
5
6
7
8
9
|
@restcontroller public class servercontroller { @getmapping ( "/msg" ) public string msg(){ return "this is product' msg" ; } } |
第一種方式
直接使用resttemplate,url寫死
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
@slf4j @restcontroller public class clientcontroller { @getmapping ( "/getproductmsg" ) public string getproductmsg(){ // 1、第一種方式(直接使用resttemplate,url寫死) resttemplate resttemplate = new resttemplate(); string response = resttemplate.getforobject( "http://localhost:9082/msg" ,string. class ); log.info( "response={}" ,response); return response; } } |
第二種方式
第二種方式(利用loadbalancerclient通過應用名獲取url,然后再使用resttemplate)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
@slf4j @restcontroller public class clientcontroller { @autowired private loadbalancerclient loadbalancerclient; @getmapping ( "/getproductmsg" ) public string getproductmsg(){ //2、第二種方式(利用loadbalancerclient通過應用名獲取url,然后再使用resttemplate) serviceinstance serviceinstance = loadbalancerclient.choose( "product" ); string url = string.format( "http://%s:%s" ,serviceinstance.gethost(),serviceinstance.getport()) + "/msg" ; resttemplate resttemplate = new resttemplate(); string response = resttemplate.getforobject(url,string. class ); log.info( "response={}" ,response); return response; } } |
第三種方式
第三種方式(利用@loadbalanced,可再resttemplate里使用應用名字)
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
|
@component public class resttemplateconfig { @bean @loadbalanced public resttemplate resttemplate(){ return new resttemplate(); } } @slf4j @restcontroller public class clientcontroller { @autowired private resttemplate resttemplate; @getmapping ( "/getproductmsg" ) public string getproductmsg(){ //3、第三種方式(利用@loadbalanced,可再resttemplate里使用應用名字) string response = resttemplate.getforobject( "http://product/msg" ,string. class ); log.info( "response={}" ,response); return response; } } |
github項目
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://segmentfault.com/a/1190000016796830