您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

RestTemplate的三种用法介绍(代码)

2025/10/3 11:44:46发布11次查看
本篇文章给大家带来的内容是关于resttemplate的三种使用方式介绍(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
准备
服务端我是用的是一个普通的api
@restcontrollerpublic class servercontroller {    @getmapping(/msg)    public string msg(){        return this is product' msg;    }}
第一种方式
直接使用resttemplate,url写死
@slf4j@restcontrollerpublic 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)@slf4j@restcontrollerpublic 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里使用应用名字)@componentpublic class resttemplateconfig {    @bean    @loadbalanced    public resttemplate resttemplate(){        return new resttemplate();    }}
@slf4j@restcontrollerpublic 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;    }}
以上就是resttemplate的三种用法介绍(代码)的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product