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 {// 创建uriURIBuilder 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:

    @AutowiredRestTemplate 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: locahostclient:register-with-eureka: falsefetch-registry: false #is false,me is eurekaService,true is notservice-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-serverdatasource:driver-class-name: com.mysql.cj.jdbc.Drivertype: com.alibaba.druid.pool.DruidDataSourceurl: jdbc:mysql://192.168.126.128:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTCusername: rootpassword: 123456
mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl#eureka配置
# eureka
eureka:client:register-with-eureka: true   #注册eurekafetch-registry: true    # 获取注册信息service-url:defaultZone: http://127.0.0.1:8084/eureka  #访问地址,一定得是ip地址和端口号!!!instance:prefer-ip-address: true  #暴露ipinstance-id: xry   #名字
management:endpoints:web:exposure:include: '*'jmx:exposure:include: '*'
info:name: qx

 启动类加上:

@EnableDiscoveryClient

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

未完,待续 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/416362.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

计算机毕业设计-----SSH超市便利店综合管理系统

项目介绍 便利店管理系统共分为两个角色&#xff1a;管理员和销售人员 销售员角色包含以下功能&#xff1a; 销售员登录,管理销售记录等功能。 管理员角色包含以下功能&#xff1a; 管理员角色登录,销售员管理,商品管理,采购管理,库存管理,销售记录管理,成本报表统计,收入报…

全面了解网络性能监测:从哪些方面进行监测?

目录 摘要 引言 CPU内存监控 磁盘监控 网络监控 GPU监控 帧率监控 总结 摘要 本文介绍了网络性能监测的重要性&#xff0c;并详细介绍了一款名为克魔助手的应用开发工具&#xff0c;该工具提供了丰富的性能监控功能&#xff0c;包括CPU、内存、磁盘、网络等指标的实时…

Pytest插件pytest-django让Django测试更高效

在Django应用开发中&#xff0c;测试是确保应用质量的关键环节。然而&#xff0c;Django自带的测试框架并非总能满足开发者的需求&#xff0c;而Pytest插件 pytest-django 则为我们提供了更为灵活、强大的测试工具。本文将深入介绍 pytest-django 插件的基本用法和实际案例&…

《WebKit 技术内幕》之四(3): 资源加载和网络栈

3. 网络栈 3.1 WebKit的网络设施 WebKit的资源加载其实是交由各个移植来实现的&#xff0c;所以WebCore其实并没有什么特别的基础设施&#xff0c;每个移植的网络实现是非常不一样的。 从WebKit的代码结构中可以看出&#xff0c;网络部分代码的确比较少的&#xff0c;它们都在…

elementUI+el-upload 上传、下载、删除文件以及文件展示列表自定义为表格展示

Upload 上传组件的使用 官方文档链接使用el-upload组件上传文件 具体参数说明&#xff0c;如何实现上传、下载、删除等功能获取文件列表进行file-list格式匹配代码 文件展示列表自定义为表格展示 使用的具体参数说明文件大小展示问题&#xff08;KB/MB&#xff09;文件下载代码…

01-开始Rust之旅

1. 下载Rust 官方推荐使用 rustup 下载 Rust&#xff0c;这是一个管理 Rust 版本和相关工具的命令行工具。下载时需要连接互联网。 这边提供了离线安装版本。本人学习的机器环境为&#xff1a; ubuntu x86_64&#xff0c;因此选用第②个工具链&#xff1b; 1. rust-1.75.0-x86_…

INTEWORK—PET 汽车软件持续集成平台

产品概述 INTEWORK-PET-CI是经纬恒润自主研发的汽车软件持续集成&持续交付平台&#xff0c;在传统的持续集成基础上深化了研运一体化&#xff08;DevOps&#xff09;的概念&#xff0c;将嵌入式软件中的拉取代码、检查、构建、测试、版本管理以及发布交付等环节串联起来&am…

Red Hat Enterprise Linux 6.10 安装图解

引导和开始安装 选择倒计时结束前&#xff0c;通过键盘上下键选择下图框选项&#xff0c;启动图形化安装过程。需要注意的不同主板默认或者自行配置的固件类型不一致&#xff0c;引导界面有所不同。也就是说使用UEFI和BIOS的安装引导界面是不同的&#xff0c;如图所示。若手动调…

市场复盘总结 20240119

仅用于记录当天的市场情况&#xff0c;用于统计交易策略的适用情况&#xff0c;以便程序回测 短线核心&#xff1a;不参与任何级别的调整&#xff0c;采用龙空龙模式 昨日主题投资 连板进级率 11/39 28.2% 二进三&#xff1a; 进级率低 43% 最常用的二种方法&#xff1a; 方…

Tensorflow2.0笔记 - 不使用layer方式,简单的MNIST训练

本笔记不使用layer相关API&#xff0c;搭建一个三层的神经网络来训练MNIST数据集。 前向传播和梯度更新都使用最基础的tensorflow API来做。 import tensorflow as tf from tensorflow import keras from tensorflow.keras import datasets import numpy as npdef load_mnist(…

一个简单的Web程序(详解创建一个Flask项目后自带的一个简单的Web程序)

程序代码截图如下&#xff1a; 1.应用初始化 在创建 Flask 程序时&#xff0c;通常需要先创建一个应用实例进行应用初始化。 from flask import Flask # 应用的初始化 app Flask(__name__) 上述代码中&#xff0c;使用 Flask 类创建了一个应用实例 app。 __name__ 参数用…

Harbor离线安装

下载安装包 $ wget https://github.com/goharbor/harbor/releases/download/v2.7.4/harbor-offline-installer-v2.7.4.tgz解压 $ tar xvf harbor-offline-installer-v2.7.4.tgz -C /usr/local修改配置 $ cd /usr/local/harbor $ cp harbor.yml.tmpl harbor.yml $ vim harbo…