0


springCloud使用apache的http类和RestTemplate以及Eureka

使用apache的:
package com.csgholding.pvgpsp.eqp.util;

import com.esotericsoftware.minlog.Log;
import org.apache.commons.collections4.MapUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;

/**
 * @Classname HttpClientUtil
 * @Date 2021/5/11 8:45
 * @Created by jj.Zhou
 */
public class HttpClientUtil {

    //字符集
    private static final String CHARSET = "UTF-8";

    private static RequestConfig defaultRequestConfig = RequestConfig
            .custom()
            //设置等待数据超时时间
            .setSocketTimeout(300000)
            //设置连接超时时间
            .setConnectTimeout(300000)
            //设置从连接池获取连接的等待超时时间
            .setConnectionRequestTimeout(300000)
            //.setStaleConnectionCheckEnabled(true)
            .build();

    //释放资源,httpResponse为响应流,httpClient为请求客户端
    private static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
        if (httpResponse != null) {
            httpResponse.close();
        }
        if (httpClient != null) {
            httpClient.close();
        }
    }
    //get请求带参数、带请求头
    public static String getAndJson(String urlWithParams, Map<String, String> header, Map<String, String> param) throws URISyntaxException {
        // 创建uri
        URIBuilder builder = new URIBuilder(urlWithParams);
        if (param != null) {
            for (String key : param.keySet()) {
                builder.addParameter(key, param.get(key));
            }
        }
        URI uri = builder.build();
        // 创建http GET请求
        HttpGet httpGet = new HttpGet(uri);
        if (!MapUtils.isEmpty(header)) {
            header.forEach(httpGet::addHeader);
        }
        CloseableHttpClient httpClient = null;
        String result;
        try {
            httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, CHARSET);
            httpGet.releaseConnection();
            release(response, httpClient);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (Exception e) {
                    Log.error(e.getMessage());
                }
            }
        }
        return result;
    }

    //get请求带参数、带请求头
    public static String get(String urlWithParams, Map<String, String> header) {
        HttpGet httpget = new HttpGet(urlWithParams);
        if (!MapUtils.isEmpty(header)) {
            header.forEach(httpget::addHeader);
        }
        CloseableHttpClient httpClient = null;
        String result;
        try {
            httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = httpClient.execute(httpget);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, CHARSET);
            httpget.releaseConnection();
            release(response, httpClient);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (Exception e) {
                    Log.error(e.getMessage());
                }
            }
        }
        return result;
    }

    public static String get(String urlWithParams) throws IOException {
        return get(urlWithParams, null);
    }

    //发送post请求,带json请求体和请求头
    public static ResponseEntity<String> postJson(String url, String json, Map<String, String> headersMap, Integer retryNum) {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(120000);
        factory.setReadTimeout(120000);

        RestTemplate restTemplate = new RestTemplate(factory);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        for (Map.Entry<String, String> entry : headersMap.entrySet()) {
            headers.add(entry.getKey(), entry.getValue());
        }
        org.springframework.http.HttpEntity<String> request = new org.springframework.http.HttpEntity<>(json, headers);
        ResponseEntity<String> response = null;
        try {
            response = restTemplate.postForEntity(url, request, String.class);
            if (retryNum > 0 && !HttpStatus.OK.equals(response.getStatusCode())) {
                retryNum--;
                postJson(url, json, headersMap, retryNum);
            }
        } catch (Exception e) {
            if (retryNum > 0) {
                retryNum--;
                postJson(url, json, headersMap, retryNum);
            } else {
                throw e;
            }
        }
        return response;
    }
}

get方法调用:

    public String callMesEqp() {
        Map<String, String> header = new HashMap<>();
        ResponseEntity<String> response;
        HttpStatus statusCode;
        String responseBody = "";
        try {
            responseBody = HttpClientUtil.get("http://127.0.0.1/t1", der);
        } catch (Throwable e) {
        }
        return responseBody;
    }

post方法调用:

    public String callMesStepEqp(String syncTime) {
        Map<String, String> header = new HashMap<>();
        ResponseEntity<String> response = null;
        HttpStatus statusCode;
        String responseBody = "";
        MesStepEqpQuery query = new MesStepEqpQuery();
        //query就是请求参数,全是字符串    
        query.setTrxDate(syncTime);
        String jsonString = JSON.toJSONString(query);
        try {
            response = HttpClientUtil.postJson("http://127.0.0.1:8080/t1, jsonString, header, 1);
        } catch (Throwable e) {
        }
        return response.getBody();
    }

使用ResTemplate:

    @Autowired
    RestTemplate restTemplate;

    @ApiOperation(value = "通过id获取用户", notes = "通过id获取用户")
    @GetMapping("getUserByIdApi")
    public Result<UserVO> getUserByIdApi(@ApiParam("用户id") Integer id) {
//        UserVO vo = restTemplate.getForObject("http://127.0.0.1:8081/v1/user/getUserById?id=" + id, UserVO.class);
        restTemplate.getForObject("http://127.0.0.1:8081/v1/user/getUserById?id=" + id, Result.class);
//        return Result.success(vo);
        return (restTemplate.getForObject("http://127.0.0.1:8081/v1/user/getUserById?id=" + id, Result.class));
    }

使用springCloud的Eureka:

注意我的jdk和cloud版本:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.cloud</groupId>
    <artifactId>springCloudPuls</artifactId>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>cloud-common</module>
        <module>cloud-user</module>
        <module>cloud-auth</module>
        <module>cloud-eureka</module>
    </modules>

    <packaging>pom</packaging>

    <properties>

    </properties>

    <dependencyManagement>
        <dependencies>
            <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-dependencies -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>2022.0.3</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>3.1.5</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--            mysql连接-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.28</version>
            </dependency>
            <!--            连接池-->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.2.16</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.13.2</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.28</version>
            </dependency>
            <!--            log4j日志-->
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
            </dependency>
            <!--            swagger-->
            <dependency>
                <groupId>io.swagger</groupId>
                <artifactId>swagger-annotations</artifactId>
                <version>1.5.20</version>
            </dependency>
            <!--            mybatis-plus-->
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>3.5.3.1</version>
            </dependency>

            <!-- https://mvnrepository.com/artifact/cn.dev33/sa-token-spring-boot3-starter -->
            <dependency>
                <groupId>cn.dev33</groupId>
                <artifactId>sa-token-spring-boot3-starter</artifactId>
                <version>1.37.0</version>
            </dependency>
        </dependencies>

    </dependencyManagement>
</project>

编写Eureka服务器:

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>

yml:

server:
  port: 8084

#eureka配置
eureka:
  instance:
    hostname: locahost
  client:
    register-with-eureka: false
    fetch-registry: false #is false,me is eurekaService,true is not
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka

springBoot启动类上加上:

@EnableEurekaServer

将服务注册进来:

        <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-eureka-client -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            <version>4.1.0</version>
        </dependency>

yml:

server:
  port: 8081
spring:
  application:
    name: cloude-user-server
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://192.168.126.128:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    username: root
    password: 123456
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

#eureka配置
# eureka
eureka:
  client:
    register-with-eureka: true   #注册eureka
    fetch-registry: true    # 获取注册信息
    service-url:
      defaultZone: http://127.0.0.1:8084/eureka  #访问地址,一定得是ip地址和端口号!!!
  instance:
    prefer-ip-address: true  #暴露ip
    instance-id: xry   #名字
management:
  endpoints:
    web:
      exposure:
        include: '*'
    jmx:
      exposure:
        include: '*'
info:
  name: qx

启动类加上:

@EnableDiscoveryClient

然后访问Eureka的页面,http://localhost:8084/

未完,待续


本文转载自: https://blog.csdn.net/qx020814/article/details/135586671
版权归原作者 菜汪在路上 所有, 如有侵权,请联系我们删除。

“springCloud使用apache的http类和RestTemplate以及Eureka”的评论:

还没有评论