欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

restTemplate實(shí)現(xiàn)跨服務(wù)API調(diào)用方式

 更新時(shí)間:2023年07月20日 14:46:44   作者:GoodStudyAndDayDayUp  
這篇文章主要介紹了restTemplate實(shí)現(xiàn)跨服務(wù)API調(diào)用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。

restTemplate跨服務(wù)API調(diào)用

同時(shí)使用ribbon,實(shí)現(xiàn)接口調(diào)用的負(fù)載均衡。

1 注冊(cè)中心

略…

2 消費(fèi)端

2.1 pom

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-ribbon</artifactId>
        </dependency>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Brixton.SR5</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

2.2 application.properties

spring.application.name=ribbon-consumer
server.port=9000
# 本地啟動(dòng)注冊(cè)中心
eureka.client.service-url.defaultZone=http://localhost:1111/eureka/

2.3 啟動(dòng)類

package com.example.lei;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@EnableDiscoveryClient
@SpringBootApplication
public class RibbonConsumerApplication {
    @Bean
    @LoadBalanced
    RestTemplate restTemplate(){
        return new RestTemplate();
    }
    public static void main(String[] args) {
        SpringApplication.run(RibbonConsumerApplication.class, args);
    }
}

2.4 消費(fèi)

package com.example.lei.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
 * @Author: leimin
 * @Description: new class
 * @Date: 2020/6/8 16:04
 * @Version: 1.0
 */
@RestController
public class ConsumerController {
    /**
     * xx
     */
    @Autowired
    RestTemplate restTemplate;
    /**
     * yyy
     * @return rr
     */
    @RequestMapping(value = "/ribbon-consumer", method = RequestMethod.GET)
    private String helloConsumer(){
        return restTemplate.getForEntity("http://HELLO-SERVICE/hello",String.class).getBody();
    }
}

3 服務(wù)端

3.1 pom

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
            <version>2.2.0.RELEASE</version>
        </dependency>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Brixton.SR5</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

3.2 application.properties

spring.application.name=hello-service
# 服務(wù)注冊(cè)到兩臺(tái)注冊(cè)中心
eureka.client.service-url.defaultZone=http://peer1:1111/eureka/,http://peer2:1112/eureka

3.3 啟動(dòng)類

package com.didispace.springboothello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
 * 能夠被發(fā)現(xiàn)為客戶端
 */
@EnableDiscoveryClient
@SpringBootApplication
public class SpringBootHelloApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootHelloApplication.class, args);
    }
}

3.4 服務(wù)

package com.didispace.springboothello.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.logging.Logger;
/**
 * @Author: leimin
 * @Description: new class
 * @Date: 2020/6/8 9:08
 * @Version: 1.0
 */
@RestController
public class HelloController {
    /**
     * xx
     */
    private final Logger logger = Logger.getLogger(String.valueOf(getClass()));
    /**
     * xx
     */
    @Autowired
    private DiscoveryClient client;
    /**
     * xx
     * @return xx
     */
    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    public String index(){
        ServiceInstance instance = client.getLocalServiceInstance();
        logger.info("/hello,host:" + instance.getHost()+", service_id:" +instance.getServiceId());
        return "hello World !";
    }
}

restTemplate實(shí)現(xiàn)跨域調(diào)用接口

本文主要針對(duì)post方式,發(fā)送請(qǐng)求。

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
/**
 * 調(diào)用mufly_api接口
 * Created by 耿洪生 on 2016/10/17.
 */
@Component
public class HttpEntityServiceImpl {
    @Value("${muflyapi.appid}")
    private String appID;
    public ResponseEntity<String> responseHttpEntity(String url, Object parameters) {
        Map<String, Object> requestObject = new HashMap<>();
        requestObject.put("appID", appID);
        requestObject.put("parameters", parameters);
        //轉(zhuǎn)json字符串
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(requestObject);
        String jsonStr = jsonObject.toJSONString();
        //設(shè)置HttpHeader
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json;charset=UTF-8");
        //設(shè)置HttpEntity
        HttpEntity<String> entity = new HttpEntity<String>(jsonStr, headers);
        //設(shè)置連接、讀取超時(shí)時(shí)間
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(30 * 1000);
        factory.setReadTimeout(60 * 1000);
        //接口調(diào)用
        RestTemplate temp = new RestTemplate(factory);
        ResponseEntity<String> output = temp.postForEntity(url, entity, String.class);
        return output;
    }
}

如果,你不想new,可以使用@Autowired直接引入:

@Autowired
private RestTemplate restTemplate;
/**
 * post請(qǐng)求
 *
 * @param url
 * @param data  map類型
 * @param token
 * @return 實(shí)體
 */
public ResponseEntity<String> post(String url, Map data, String token) {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Accept", "application/json");
    headers.add("Accept-Encoding", "gzip");
    headers.add("Content-Encoding", "UTF-8");
    headers.add("Content-Type", "application/json;charset=UTF-8");
    headers.add("Token", token);
    String dataStr = JsonUtil.toJSon(data);
    HttpEntity<String> postEntity = new HttpEntity<>(dataStr, headers);
    return restTemplate.postForEntity(url, postEntity, String.class);
}

至于設(shè)置restTemplate bean 的超時(shí):

@Bean(name="restTemplate")
RestTemplate restTemplate() {
   ClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
       //設(shè)置連接、讀取超時(shí)時(shí)間
       ((SimpleClientHttpRequestFactory) factory).setConnectTimeout(30 * 1000);
       ((SimpleClientHttpRequestFactory) factory).setReadTimeout(60 * 1000);
   return new RestTemplate();
}

spring自帶的restTemplate里有很多實(shí)用的方法,

其底層還是ClientHttpRequest,

總結(jié)

以此記錄。以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java使用線程池批量處理數(shù)據(jù)操作具體流程

    Java使用線程池批量處理數(shù)據(jù)操作具體流程

    這篇文章主要給大家介紹了關(guān)于Java使用線程池批量處理數(shù)據(jù)操作的相關(guān)資料,Java多線程編程中線程池是一個(gè)非常重要的概念,線程池可以提高線程的復(fù)用率和任務(wù)調(diào)度的效率,尤其是當(dāng)需要查詢大批量數(shù)據(jù)時(shí),需要的朋友可以參考下
    2023-06-06
  • JavaSE static final及abstract修飾符實(shí)例解析

    JavaSE static final及abstract修飾符實(shí)例解析

    這篇文章主要介紹了JavaSE static final及abstract修飾符實(shí)例解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-06-06
  • Java實(shí)現(xiàn)驗(yàn)證文件名有效性的方法詳解

    Java實(shí)現(xiàn)驗(yàn)證文件名有效性的方法詳解

    在本文中,我們將討論使用?Java?驗(yàn)證一個(gè)給定的字符串是否具有操作系統(tǒng)的有效文件名的不同方法,文中的示例代碼講解詳細(xì),感興趣的可以了解一下
    2022-09-09
  • 淺談JAVA Actor模型的一致性與隔離性

    淺談JAVA Actor模型的一致性與隔離性

    這篇文章主要介紹了JAVA Actor模型的的相關(guān)資料,文中講解非常細(xì)致,幫助大家更好的學(xué)習(xí)JAVA,感興趣的朋友可以了解下
    2020-06-06
  • java 非對(duì)稱加密算法RSA實(shí)現(xiàn)詳解

    java 非對(duì)稱加密算法RSA實(shí)現(xiàn)詳解

    這篇文章主要介紹了java 非對(duì)稱加密算法RSA實(shí)現(xiàn)詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-07-07
  • Spring Boot 中的 @PutMapping 注解原理及使用小結(jié)

    Spring Boot 中的 @PutMapping 注解原理及使用小結(jié)

    在本文中,我們介紹了 Spring Boot 中的 @PutMapping 注解,它可以將 HTTP PUT 請(qǐng)求映射到指定的處理方法上,我們還介紹了 @PutMapping 注解的原理以及如何在 Spring Boot 中使用它,感興趣的朋友跟隨小編一起看看吧
    2023-12-12
  • JDK動(dòng)態(tài)代理與CGLib動(dòng)態(tài)代理的區(qū)別對(duì)比

    JDK動(dòng)態(tài)代理與CGLib動(dòng)態(tài)代理的區(qū)別對(duì)比

    今天小編就為大家分享一篇關(guān)于JDK動(dòng)態(tài)代理與CGLib動(dòng)態(tài)代理的區(qū)別對(duì)比,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
    2019-02-02
  • SpringCloud HystrixDashboard服務(wù)監(jiān)控詳解

    SpringCloud HystrixDashboard服務(wù)監(jiān)控詳解

    Hystrix Dashboard 是Spring Cloud中查看Hystrix實(shí)例執(zhí)行情況的一種儀表盤組件,支持查看單個(gè)實(shí)例和查看集群實(shí)例,本文將對(duì)其服務(wù)監(jiān)控學(xué)習(xí)
    2022-11-11
  • Redis六大數(shù)據(jù)類型使用方法詳解

    Redis六大數(shù)據(jù)類型使用方法詳解

    這篇文章主要介紹了Redis六大數(shù)據(jù)類型使用方法詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-12-12
  • 關(guān)于idea-web.xml版本過(guò)低怎么生成新的(web.xml報(bào)錯(cuò))問(wèn)題

    關(guān)于idea-web.xml版本過(guò)低怎么生成新的(web.xml報(bào)錯(cuò))問(wèn)題

    今天通過(guò)本文給大家分享idea-web.xml版本過(guò)低怎么生成新的(web.xml報(bào)錯(cuò))問(wèn)題,通過(guò)更換web.xml版本解決此問(wèn)題,感興趣的朋友跟隨小編一起看看吧
    2021-07-07

最新評(píng)論