Commit 6d6a725e by 穆龙飞

modify:修改邮件发送逻辑

parent 1c11b477
env=online
dschedule.enable=true dschedule.enable=true
dschedule.env=online dschedule.env=online
dschedule.app-id=yanxuan-sc-ehc dschedule.app-id=yanxuan-sc-ehc
......
env=test
dschedule.enable=true dschedule.enable=true
dschedule.env=test dschedule.env=test
dschedule.app-id=yanxuan-qc-change-system dschedule.app-id=yanxuan-qc-change-system
......
package com.netease.mail.yanxuan.change.integration.client;
public interface Checker {
/**
* 校验结果是否成功
*
* @return
*/
boolean check();
}
/**
* @(#)HttpClientTemplate.java, 2015年9月8日.
*
* Copyright 2015 Netease, Inc. All rights reserved.
* NETEASE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package com.netease.mail.yanxuan.change.integration.client;
import com.alibaba.fastjson.JSON;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
/**
* Http工具类
* <p>
* 本工具类主要针对常用的GET和POST请求进行了封装并提供了方便的HTTP调用接口
* <p>
* 对于常见的GET和POST请求,只需要指定url、参数和编码方式即可方便调用,参见
* <li>{@code executeGet(url)}
* <li>{@code executeGet(url, parameters)}
* <li>{@code executeGet(url, parameters, charset)}
* <li>{@code executePost(url)}
* <li>{@code executePost(url, parameters)}
* <li>{@code executePost(url, parameters, charset)}
*
* @author hzyurui
*/
@Component("httpClientTemplate")
public class HttpClientTemplate {
private static final Logger logger = LoggerFactory.getLogger(HttpClientTemplate.class);
private HttpClient httpClient;
private HttpClient httpsTrustAnyClient;
protected int getTimeout() {
return 50000;
}
protected int getMaxTotal() {
return 500;
}
protected int getDefaultMaxPerRoute() {
return 100;
}
protected String getDefaultCharset() {
return "utf-8";
}
@PostConstruct
public void init() {
SSLContext sslContext = null;
try {
sslContext = new SSLContextBuilder().loadTrustMaterial(null, TrustAnyStrategy.get()).build();
} catch (Throwable t) {
throw new RuntimeException(t);
}
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
new NoopHostnameVerifier());
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", sslConnectionSocketFactory)
.register("http", PlainConnectionSocketFactory.getSocketFactory()).build();
PoolingHttpClientConnectionManager httpsConnectionManager = new PoolingHttpClientConnectionManager(
socketFactoryRegistry);
httpsConnectionManager.setMaxTotal(getMaxTotal());
httpsConnectionManager.setDefaultMaxPerRoute(getDefaultMaxPerRoute());
httpsTrustAnyClient = HttpClients.custom().setConnectionManager(httpsConnectionManager).build();
PoolingHttpClientConnectionManager httpConnectionManager = new PoolingHttpClientConnectionManager(
socketFactoryRegistry);
httpConnectionManager.setMaxTotal(getMaxTotal());
httpConnectionManager.setDefaultMaxPerRoute(getDefaultMaxPerRoute());
httpClient = HttpClients.custom().setConnectionManager(httpConnectionManager).build();
}
public HttpClient getHttpClient() {
return this.httpClient;
}
public HttpClient getHttpsTrustAnyClient() {
return httpsTrustAnyClient;
}
/**
* 使用默认编码执行执行无参数的POST请求并将响应实体以字符串返回
*
* @param url
* url
* @return
* @throws IOException
*/
public String executePost(String url) throws IOException, HttpException {
return executePost(url, null);
}
/**
* 文件传输post请求
* <p>
* 执行无参数的POST请求传输文件,并将响应实体以字符串返回
*
* @param url
* @param filePath
* @return
*/
public String executeFilePost(String url, List<NameValuePair> parameters, String filePath)
throws IOException, HttpException {
File file = new File(filePath);
if (file.exists()) {
return executeFilePost(url, parameters, file);
} else {
logger.error("[op:executeFilePost] HttpClientTemplate.executeFilePost file is not exist! filePath={} ",
filePath);
}
return null;
}
/**
* 文件传输post请求
* <p>
* 执行无参数的POST请求传输文件,并将响应实体以字符串返回
*
* @param url
* @param file
* @return
*/
public String executeFilePost(String url, List<NameValuePair> parameters, File file)
throws IOException, HttpException {
String result = "";
if (file != null && file.exists()) {
HttpPost httpPost = getHttpPost(url);
FileBody bin = new FileBody(file);
MultipartEntityBuilder builder = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE).setCharset(Charset.forName("UTF-8"))
.addPart("file", bin);
httpPost.setEntity(builder.build());
if (logger.isDebugEnabled()) {
logger.debug("[op:executePost] making post request url={}, fileName={}, totalSpace={}", url,
file.getName(), file.getTotalSpace());
}
//文件传输
HttpResponse response = httpClient.execute(httpPost);
result = getResponseContentStr(response, null);
if (logger.isDebugEnabled()) {
logger.debug("[op:HttpClientTemplate] response from url={}, fileName={}, response={}", url,
file.getName(), result);
}
} else {
logger.error("[op:executeFilePost] HttpClientTemplate.executeFilePost file is not exist!");
}
return result;
}
/**
* 使用默认编码执行POST请求并将响应实体以字符串返回
*
* @param url
* url
* @param parameters
* 参数
* @return
* @throws IOException
*/
public String executePost(String url, List<NameValuePair> parameters) throws IOException, HttpException {
return executePost(url, parameters, null, false);
}
/**
* 使用默认编码执行POST请求并将响应实体以字符串返回
*
* @param url
* url
* @param parameters
* 参数
* @param timeout
* 超时时间
* @return
* @throws IOException
*/
public String executePost(String url, List<NameValuePair> parameters, int timeout)
throws IOException, HttpException {
return executePost(url, parameters, null, timeout);
}
/**
* 执行POST请求并将响应实体以字符串返回
*
* @param url
* url
* @param parameters
* 参数
* @param charset
* 编码,若为null则使用默认编码
* @return
* @throws IOException
*/
public String executePost(String url, List<NameValuePair> parameters, String charset, boolean isTrustAny)
throws IOException, HttpException {
return executePost(url, parameters, charset, 0, isTrustAny);
// charset = charset != null ? charset : getDefaultCharset();
// HttpPost postRequest = makePostRequest(url, parameters, charset);
// String result = requestAndParse(postRequest, charset, isTrustAny);
// if (logger.isDebugEnabled()) {
// logger.debug(
// "[op:HttpClientTemplate] response from url={}, param={}, data={}",
// url, JSON.toJSON(parameters), result);
// }
// return result;
}
/**
* 执行POST请求并将响应实体以字符串返回
*
* @param url
* url
* @param parameters
* 参数
* @param charset
* 编码,若为null则使用默认编码
* @param timeout
* 超时时间
* @return
* @throws IOException
*/
public String executePost(String url, List<NameValuePair> parameters, String charset, int timeout)
throws IOException, HttpException {
return executePost(url, parameters, charset, timeout, false);
// charset = charset != null ? charset : getDefaultCharset();
// HttpPost postRequest = makePostRequest(url, parameters, charset,
// timeout);
// String result = requestAndParse(postRequest, charset);
// if (logger.isDebugEnabled()) {
// logger.debug(
// "[op:HttpClientTemplate] response from url={}, param={}, timeout={}, data={}",
// url, JSON.toJSON(parameters), timeout, result);
// }
// return result;
}
/**
* 执行POST请求并将响应实体以字符串返回
*
* @param url
* url
* @param parameters
* 参数
* @param charset
* 编码,若为null则使用默认编码
* @param timeout
* 超时时间
* @return
* @throws IOException
*/
public String executePost(String url, List<NameValuePair> parameters, String charset, int timeout,
boolean isTrustAny) throws IOException, HttpException {
charset = charset != null ? charset : getDefaultCharset();
HttpPost postRequest = makePostRequest(url, parameters, charset, timeout);
String result = requestAndParse(postRequest, charset, isTrustAny);
if (logger.isDebugEnabled()) {
logger.debug("[op:HttpClientTemplate] response from url={}, param={}, timeout={}, data={}", url,
JSON.toJSON(parameters), timeout, result);
}
return result;
}
/**
* 执行POST请求并将响应实体以字符串返回
*
* @param url
* url
* @param stringEntity
* 请求内容体,默认为json格式
* @param charset
* 编码,若为null则使用默认编码
* @return
* @throws IOException
*/
public String executePost(String url, String stringEntity, String charset) throws IOException, HttpException {
return executePost(url, stringEntity, charset, 0);
// charset = charset != null ? charset : getDefaultCharset();
// HttpPost postRequest = makePostRequest(url, stringEntity, charset);
// String result = requestAndParse(postRequest, charset);
// if (logger.isDebugEnabled()) {
// logger.debug(
// "[op:HttpClientTemplate] response from url={}, entity={}, data={}",
// url, stringEntity, result);
// }
// return result;
}
/**
* 执行POST请求并将响应实体以字符串返回
*
* @param url
* url
* @param stringEntity
* 请求内容体,默认为json格式
* @param charset
* 编码,若为null则使用默认编码
* @param timeout
* @return
* @throws IOException
*/
public String executePost(String url, String stringEntity, String charset, int timeout)
throws IOException, HttpException {
return executePost(url, stringEntity, charset, timeout, null);
}
/**
* 执行POST请求并将响应实体以字符串返回
*
* @param url
* url
* @param stringEntity
* 请求内容体,默认为json格式
* @param charset
* 编码,若为null则使用默认编码
* @param timeout
* 超时时间
* @param headers
* 自定义header
* @return
* @throws IOException
*/
public String executePost(String url, String stringEntity, String charset, int timeout, Map<String, String> headers)
throws IOException, HttpException {
charset = charset != null ? charset : getDefaultCharset();
HttpPost postRequest = makePostRequest(url, stringEntity, charset, timeout);
if (null != headers) {
for (Map.Entry<String, String> header: headers.entrySet()) {
postRequest.setHeader(header.getKey(), header.getValue());
}
}
String result = requestAndParse(postRequest, charset);
if (logger.isDebugEnabled()) {
logger.debug("[op:HttpClientTemplate] response from url={}, entity={}, data={}, timeout={}", url,
stringEntity, result, timeout);
}
return result;
}
/**
* 执行POST请求并将响应实体以字符串返回
*
* @param url
* url
* @param httpEntity
* 请求内容体
* @param charset
* 编码,若为null则使用默认编码
* @return
* @throws IOException
*/
public String executePost(String url, HttpEntity httpEntity, String charset) throws IOException, HttpException {
return executePost(url, httpEntity, charset, 0);
// charset = charset != null ? charset : getDefaultCharset();
// HttpPost postRequest = makePostRequest(url, httpEntity, charset);
// String result = requestAndParse(postRequest, charset);
// if (logger.isDebugEnabled()) {
// logger.debug(
// "[op:HttpClientTemplate] response from url={}, httpEntity={}, data={}",
// url, httpEntity, result);
// }
// return result;
}
/**
* 执行POST请求并将响应实体以字符串返回
*
* @param url
* url
* @param httpEntity
* 请求内容体
* @param charset
* 编码,若为null则使用默认编码
* @return
* @throws IOException
*/
public String executePost(String url, HttpEntity httpEntity, String charset, int timeout)
throws IOException, HttpException {
charset = charset != null ? charset : getDefaultCharset();
HttpPost postRequest = makePostRequest(url, httpEntity, charset, timeout);
String result = requestAndParse(postRequest, charset);
if (logger.isDebugEnabled()) {
logger.debug("[op:HttpClientTemplate] response from url={}, httpEntity={}, data={}", url, httpEntity,
result);
}
return result;
}
/**
* 使用默认的编码执行无参数的GET请求并将响应实体以字符串返回
*
* @param url
* url
* @return
* @throws IOException
*/
public String executeGet(String url) throws IOException, HttpException {
return executeGet(url, null);
}
/**
* 使用默认的编码执行无参数的GET请求并将响应实体以字符串返回
*
* @param url
* url
* @return
* @throws IOException
*/
public String executeGet(String url, int timeout) throws IOException, HttpException {
return executeGet(url, null, timeout);
}
/**
* 使用默认的编码执行GET请求并将响应实体以字符串返回
*
* @param url
* url
* @param parameters
* 参数
* @return
* @throws IOException
*/
public String executeGet(String url, List<NameValuePair> parameters) throws IOException, HttpException {
return executeGet(url, parameters, null, false);
}
/**
* 使用默认的编码执行GET请求并将响应实体以字符串返回
*
* @param url
* url
* @param parameters
* 参数
* @return
* @throws IOException
*/
public String executeGet(String url, List<NameValuePair> parameters, int timeout)
throws IOException, HttpException {
return executeGet(url, parameters, null, false, timeout);
}
/**
* 执行GET请求并将响应实体以字符串返回
*
* @param url
* url
* @param parameters
* 参数
* @param charset
* 编码,若为null则使用默认编码
* @param isTrustAny
* 是否信任所访问站点
* @return
* @throws IOException
*/
public String executeGet(String url, List<NameValuePair> parameters, String charset, boolean isTrustAny)
throws IOException, HttpException {
return executeGet(url, parameters, charset, isTrustAny, 0);
// charset = charset != null ? charset : getDefaultCharset();
// HttpGet getRequest = makeGetRequest(url, parameters, charset);
// if (logger.isDebugEnabled()) {
// logger.debug("[op:executeGet] getRequest={}",
// JSON.toJSON(getRequest));
// }
// String result = requestAndParse(getRequest, charset, isTrustAny);
// if (logger.isDebugEnabled()) {
// logger.debug(
// "[op:executeGet] response from url={}, param={}, data={}", url,
// JSON.toJSON(parameters), result);
// }
// return result;
}
/**
* 执行GET请求并将响应实体以字符串返回
*
* @param url
* url
* @param parameters
* 参数
* @param charset
* 编码,若为null则使用默认编码
* @param isTrustAny
* 是否信任所访问站点
* @return
* @throws IOException
*/
public String executeGet(String url, List<NameValuePair> parameters, String charset, boolean isTrustAny,
int timeout) throws IOException, HttpException {
return executeGet(url, parameters, charset, isTrustAny, timeout, null);
}
public String executeGet(String url, List<NameValuePair> parameters, String charset, boolean isTrustAny,
int timeout, Map<String, String> headers) throws IOException, HttpException {
charset = charset != null ? charset : getDefaultCharset();
HttpGet getRequest = makeGetRequest(url, parameters, charset);
if (null != headers) {
for (Map.Entry<String, String> header: headers.entrySet()) {
getRequest.setHeader(header.getKey(), header.getValue());
}
}
if (logger.isDebugEnabled()) {
logger.debug("[op:executeGet] getRequest={}", JSON.toJSON(getRequest));
}
String result = requestAndParse(getRequest, charset, isTrustAny);
if (logger.isDebugEnabled()) {
logger.debug("[op:executeGet] response from url={}, param={}, data={}", url, JSON.toJSON(parameters),
result);
}
return result;
}
/**
* 执行GET请求并将响应实体以HttpResponse返回
*
* @param url
* url
* @param parameters
* 参数
* @param charset
* 编码,若为null则使用默认编码
* @return
* @throws IOException
*/
public HttpResponse executeFileGet(String url, List<NameValuePair> parameters, String charset, int timeout)
throws IOException {
charset = charset != null ? charset : getDefaultCharset();
HttpGet httpGet = makeGetRequest(url, parameters, charset, timeout);
HttpResponse httpResponse = httpClient.execute(httpGet);
if (logger.isDebugEnabled()) {
logger.debug("[op:executeFileGet] response from url={}, param={}", url, JSON.toJSON(parameters));
}
return httpResponse;
}
public HttpResponse executeFilePost(String url, String filePath, String charset) throws IOException {
// charset = charset != null ? charset : defaultCharset;
File file = new File(filePath);
if (file != null && file.exists()) {
HttpPost httpPost = getHttpPost(url);
FileBody bin = new FileBody(file);
StringBody fileName = new StringBody(file.getName(), ContentType.TEXT_PLAIN);
MultipartEntityBuilder builder = MultipartEntityBuilder.create().addPart("file", bin).addPart("fileName",
fileName);
httpPost.setEntity(builder.build());
if (logger.isDebugEnabled()) {
logger.debug("[op:executePost] making post request url={}, fileName={}", url, file.getName());
}
HttpResponse httpResponse = httpClient.execute(httpPost);
if (logger.isDebugEnabled()) {
logger.debug("[op:executeFilePost] response from url={}, param={}", url);
}
return httpResponse;
}
return null;
}
/**
* 根据给定的url、参数和编码方式构建一个GET请求
*
* @param url
* url
* @param parameters
* 参数
* @param charset
* 编码,若为null则使用默认编码
* @return
*/
private HttpGet makeGetRequest(String url, List<NameValuePair> parameters, String charset) {
String queryString = null;
if (parameters != null && parameters.size() > 0) {
charset = charset != null ? charset : getDefaultCharset();
queryString = URLEncodedUtils.format(parameters, charset);
}
String requestUrl = url;
if (queryString != null) {
if (url.indexOf("?") == -1)
requestUrl += "?" + queryString;
else
requestUrl += "&" + queryString;
}
if (logger.isDebugEnabled()) {
logger.debug("[op:makeGetRequest] making get request url={}", requestUrl);
}
return getHttpGet(requestUrl);
}
/**
* 根据给定的url、参数和编码方式构建一个GET请求
*
* @param url
* url
* @param parameters
* 参数
* @param charset
* 编码,若为null则使用默认编码
* @param timeout
* 超时时间
* @return
*/
private HttpGet makeGetRequest(String url, List<NameValuePair> parameters, String charset, int timeout) {
String queryString = null;
if (parameters != null && parameters.size() > 0) {
charset = charset != null ? charset : getDefaultCharset();
queryString = URLEncodedUtils.format(parameters, charset);
}
String requestUrl = url;
if (queryString != null) {
if (url.indexOf("?") == -1)
requestUrl += "?" + queryString;
else
requestUrl += "&" + queryString;
}
if (logger.isDebugEnabled()) {
logger.debug("[op:makeGetRequest] making get request url={}, timeout={}", requestUrl, timeout);
}
return getHttpGet(requestUrl, timeout);
}
/**
* 根据给定的url、参数和编码方式构建一个POST请求
*
* @param url
* url
* @param parameters
* 参数
* @param charset
* 编码,若为null则使用默认编码
* @return
*/
private HttpPost makePostRequest(String url, List<NameValuePair> parameters, String charset) throws IOException {
HttpPost post = getHttpPost(url);
if (parameters != null && parameters.size() > 0) {
charset = charset != null ? charset : getDefaultCharset();
UrlEncodedFormEntity urfe = new UrlEncodedFormEntity(parameters, charset);
post.setEntity(urfe);
if (logger.isDebugEnabled()) {
logger.debug("[op:makePostRequest] making post request url={}, param={}", url, JSON.toJSON(parameters));
}
}
return post;
}
/**
* 根据给定的url、参数和编码方式构建一个POST请求
*
* @param url
* url
* @param parameters
* 参数
* @param charset
* 编码,若为null则使用默认编码
* @param timeout
* 超时时间
* @return
*/
private HttpPost makePostRequest(String url, List<NameValuePair> parameters, String charset, int timeout)
throws IOException {
HttpPost post = getHttpPost(url, timeout);
if (parameters != null && parameters.size() > 0) {
charset = charset != null ? charset : getDefaultCharset();
UrlEncodedFormEntity urfe = new UrlEncodedFormEntity(parameters, charset);
post.setEntity(urfe);
if (logger.isDebugEnabled()) {
logger.debug("[op:makePostRequest] making post request url={}, param={}, timeout={}", url,
JSON.toJSON(parameters), timeout);
}
}
return post;
}
/**
* 根据给定的url、参数和编码方式构建一个POST请求
*
* @param url
* url
* @param stringEntity
* 请求内容体,默认为json格式
* @param charset
* 编码,若为null则使用默认编码
* @return
*/
private HttpPost makePostRequest(String url, String stringEntity, String charset, int timeout) throws IOException {
HttpPost post = getHttpPost(url, timeout);
if (stringEntity != null) {
//charset = charset != null ? charset : defaultCharset;
StringEntity se = new StringEntity(stringEntity, ContentType.APPLICATION_JSON);
post.setEntity(se);
if (logger.isDebugEnabled()) {
logger.debug("[op:makePostRequest] making post request url={}, entity={}", url, stringEntity);
}
}
return post;
}
/**
* 根据给定的url、参数和编码方式构建一个POST请求
*
* @param url
* url
* @param httpEntity
* 请求内容体
* @param charset
* 编码,若为null则使用默认编码
* @return
*/
private HttpPost makePostRequest(String url, HttpEntity httpEntity, String charset, int timeout)
throws IOException {
HttpPost post = getHttpPost(url, timeout);
if (httpEntity != null) {
post.setEntity(httpEntity);
}
return post;
}
/**
* 生成POST请求,使用配置的参数
*
* @param url
* @return
*/
private HttpPost getHttpPost(String url) {
return getHttpPost(url, 0);
// HttpPost postMethod = new HttpPost(url);
// RequestConfig requestConfig = RequestConfig.custom()
// .setConnectTimeout(getTimeout()).setConnectionRequestTimeout(getTimeout())
// .setSocketTimeout(getTimeout()).setRedirectsEnabled(false).build();
// postMethod.setConfig(requestConfig);
// return postMethod;
}
/**
* 生成POST请求,使用配置的参数
*
* @param url
* @param timeout
* @return
*/
private HttpPost getHttpPost(String url, int timeout) {
if (timeout <= 0) {
timeout = getTimeout();
}
HttpPost postMethod = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).setRedirectsEnabled(false).build();
postMethod.setConfig(requestConfig);
return postMethod;
}
/**
* 生成GET请求,使用配置的参数
*
* @param url
* @return
*/
private HttpGet getHttpGet(String url) {
return getHttpGet(url, 0);
// HttpGet getMethod = new HttpGet(url);
// RequestConfig requestConfig = RequestConfig.custom()
// .setConnectTimeout(getTimeout())
// .setConnectionRequestTimeout(getTimeout())
// .setSocketTimeout(getTimeout()).setRedirectsEnabled(false).build();
// getMethod.setConfig(requestConfig);
// return getMethod;
}
/**
* 生成GET请求,使用配置的参数
*
* @param url
* @param timeout
* @return
*/
private HttpGet getHttpGet(String url, int timeout) {
if (timeout <= 0) {
timeout = getTimeout();
}
HttpGet getMethod = new HttpGet(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).setRedirectsEnabled(false).build();
getMethod.setConfig(requestConfig);
return getMethod;
}
/**
* 执行请求并获取响应
*
* @param httpRequest
* HTTP请求
* @param charset
* 响应体编码
* @return
* @throws ClientProtocolException
* @throws IOException,HttpException
*/
private String requestAndParse(HttpUriRequest httpRequest, String charset) throws IOException, HttpException {
return requestAndParse(httpRequest, charset, false);
}
/**
* 执行请求并获取响应,支持信任所有被访问站点的请求
*
* @param httpRequest
* @param charset
* @param isTrustAny
* @return
* @throws IOException,HttpException
*/
private String requestAndParse(HttpUriRequest httpRequest, String charset, boolean isTrustAny)
throws IOException, HttpException {
HttpResponse httpResponse = isTrustAny ? httpsTrustAnyClient.execute(httpRequest)
: httpClient.execute(httpRequest);
return getResponseContentStr(httpResponse, charset);
}
/**
* 使用指定编码将响应实体转为字符串
*
* @param httpResponse
* 响应
* @param charset
* 编码
* @return
* @throws IOException,HttpException
*/
private String getResponseContentStr(HttpResponse httpResponse, String charset) throws IOException, HttpException {
HttpEntity entity = getResponseContentEntity(httpResponse);
if (null == entity) {
return null;
}
return EntityUtils.toString(entity, getDefaultCharset());
}
/**
* 获取响应实体
*
* @param httpResponse
* @return
* @throws IOException
*/
private HttpEntity getResponseContentEntity(HttpResponse httpResponse) throws HttpException {
StatusLine statusLine = httpResponse.getStatusLine();
if (null == statusLine) {
throw new HttpException("status not specified");
}
int statusCode = statusLine.getStatusCode();
if (statusCode < 200 || statusCode > 299) {
EntityUtils.consumeQuietly(httpResponse.getEntity());
throw new HttpException("status code: " + statusCode);
}
return httpResponse.getEntity();
}
}
package com.netease.mail.yanxuan.change.integration.client;
public class LabelLevel {
/**
* 分类信息,100:色情,110:性感,200:广告,210:二维码,300:暴恐,400:违禁,500:涉政
*/
private int label;
/**
* 分类级别,0:正常,1:不确定,2:确定
*/
private int level;
public LabelLevel() {}
public LabelLevel(int label, int level) {
this.label = label;
this.level = level;
}
public int getLabel() {
return label;
}
public void setLabel(int label) {
this.label = label;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
}
package com.netease.mail.yanxuan.change.integration.client;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netease.mail.yanxuan.change.integration.rpc.RpcResultException;
import java.io.IOException;
import java.util.List;
public class RpcListResult<T> implements RpcTemplate.CallHandler<List<T>> {
private final Class<T> tClass;
public RpcListResult(Class<T> tClass) {
this.tClass = tClass;
}
@Override
public List<T> handle(String resp) throws IOException {
JSONObject rpcResult = JSON.parseObject(resp);
int code = rpcResult.getIntValue("code");
if (code == 200) {
return JSON.parseArray(rpcResult.getString("result"), tClass);
}
throw new RpcResultException("response error, code = " + code);
}
}
package com.netease.mail.yanxuan.change.integration.client;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netease.mail.yanxuan.change.integration.rpc.RpcResultException;
import java.io.IOException;
public class RpcObjectData<T> implements RpcTemplate.CallHandler<T> {
private Class<T> tClass;
public RpcObjectData(Class<T> tClass) {
this.tClass = tClass;
}
@Override
public T handle(String resp) throws IOException {
JSONObject rpcResult = JSON.parseObject(resp);
int code = rpcResult.getIntValue("code");
if (code == 200) {
return JSON.parseObject(rpcResult.getString("data"), tClass);
}
throw new RpcResultException("response error, code = " + code);
}
}
package com.netease.mail.yanxuan.change.integration.client;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netease.mail.yanxuan.change.integration.rpc.RpcResultException;
import lombok.SneakyThrows;
import java.io.IOException;
public class RpcObjectDataMsg<T> implements RpcTemplate.CallHandler<T> {
private Class<T> tClass;
public RpcObjectDataMsg(Class<T> tClass) {
this.tClass = tClass;
}
@SneakyThrows
@Override
public T handle(String resp) throws IOException {
JSONObject rpcResult = JSON.parseObject(resp);
int code = rpcResult.getIntValue("code");
if (code == 200) {
return JSON.parseObject(rpcResult.getString("data"), tClass);
}
throw new RpcResultException(rpcResult.getString("msg"));
}
}
package com.netease.mail.yanxuan.change.integration.client;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netease.mail.yanxuan.change.integration.rpc.RpcResultException;
import java.io.IOException;
public class RpcObjectResult<T> implements RpcTemplate.CallHandler<T> {
private Class<T> tClass;
public RpcObjectResult(Class<T> tClass) {
this.tClass = tClass;
}
@Override
public T handle(String resp) throws IOException {
JSONObject rpcResult = JSON.parseObject(resp);
int code = rpcResult.getIntValue("code");
if (code == 200) {
return JSON.parseObject(rpcResult.getString("result"), tClass);
}
throw new RpcResultException("response error, code = " + code);
}
}
package com.netease.mail.yanxuan.change.integration.client;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.netease.mail.yanxuan.change.integration.email.exception.RpcException;
import com.netease.mail.yanxuan.change.integration.email.exception.RpcTimeoutException;
import com.netease.mail.yanxuan.change.integration.email.util.EncodeUtil;
import com.netease.mail.yanxuan.change.integration.email.util.HttpClientUtil;
import com.netease.yanxuan.missa.pressure.TracerClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.util.List;
import java.util.Map;
@Component
public class RpcTemplate {
private static final Logger LOG = LoggerFactory.getLogger(RpcTemplate.class);
@Value("${act.rpc.get.retry:1}")
private int rpcGetRetry;
@Value("${act.rpc.post.retry:0}")
private int rpcPostRetry;
@Value("${act.rpc.collect:false}")
private boolean rpcCollect;
public RpcTemplate() {
ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
}
/**
* Get请求
*
* @param url
* @param handler
* @param <T>
* @return
*/
public <T> T get(String url, CallHandler<T> handler) {
return get(url, null, null, -1, handler);
}
/**
* Get请求
*
* @param url
* @param params
* @param handler
* @param <T>
* @return
*/
public <T> T get(String url, Map<String, Object> params, CallHandler<T> handler) {
return get(url, params, null, -1, handler);
}
/**
* Get请求
*
* @param url
* @param params
* @param header
* @param timeout
* @param handler
* @param <T>
* @return
*/
public <T> T get(String url, Map<String, Object> params, Map<String, String> header,
int timeout, CallHandler<T> handler) {
CallTemplate template = () -> HttpClientUtil.get(url, params, header, timeout);
return this.execute(url, params, handler, template, rpcGetRetry, Method.GET);
}
/**
* Post请求
*
* @param url
* @param params
* @param handler
* @param <T>
* @return
*/
public <T> T post(String url, Map<String, Object> params, CallHandler<T> handler) {
return post(url, params, -1, handler);
}
/**
* Post请求
*
* @param url
* @param params
* @param timeout
* @param handler
* @param <T>
* @return
*/
public <T> T post(String url, Map<String, Object> params, int timeout, CallHandler<T> handler) {
CallTemplate template = () -> HttpClientUtil.post(url, params, timeout);
return this.execute(url, params, handler, template, rpcPostRetry, Method.POST);
}
/**
* Post Json请求
*
* @param url
* @param params
* @param handler
* @param <T>
* @return
*/
public <T> T postJson(String url, String params, CallHandler<T> handler) {
return postJson(url, params, -1, handler);
}
/**
* Post Json请求
*
* @param url
* @param params
* @param timeout
* @param handler
* @param <T>
* @return
*/
public <T> T postJson(String url, String params, int timeout, CallHandler<T> handler) {
CallTemplate template = () -> HttpClientUtil.postJson(url, params, timeout);
return this.execute(url, params, handler, template, rpcPostRetry, Method.BODY);
}
/**
* 执行模板调用
*
* @param url
* 请求地址
* @param params
* 请求报文
* @param handler
* 返回解析
* @param callTemplate
* 模板调用
* @param retryTime
* 最多重复次数,0默认(3次)
*/
private <T> T execute(String url, Object params, CallHandler<T> handler,
CallTemplate callTemplate, int retryTime, Method method) {
int tryTimes = 0;
RpcException rpcException = null;
String respBody = null;
RpcStatus status = RpcStatus.SUCCESS;
while (tryTimes <= retryTime) {
long startTime = System.currentTimeMillis();
try {
respBody = callTemplate.executeCall();
if (StringUtils.isEmpty(respBody)) {
throw new RpcException("response empty");
}
T t = handler.handle(respBody);
status = checkResp(handler, t);
return t;
} catch (RpcTimeoutException e) {
rpcException = e;
status = RpcStatus.TIMEOUT;
} catch (RpcException e) {
rpcException = e;
status = RpcStatus.EXCEPTION;
} catch (Exception e) {
rpcException = new RpcException(e);
status = RpcStatus.EXCEPTION;
} finally {
try {
if (LOG.isDebugEnabled() || rpcCollect) {
long costTime = System.currentTimeMillis() - startTime;
String reqParam = convertParam(params);
// 根据需要开启rpc日志
if (LOG.isDebugEnabled()) {
LOG.debug(
"process request, yx-tracer-flowType={}, url={}, method={}, params={}, response={}, cost={}ms",
TracerClient.getFlowType(), url, method.name(), reqParam, respBody,
costTime);
}
}
} catch (Exception e) {
LOG.error("collect error, msg={}", e.getMessage());
}
}
tryTimes++;
}
LOG.error("request error, url={}, params={}, respBody={}", url,
params instanceof String ? params : JSON.toJSONString(params), respBody, rpcException);
if (rpcException == null) {
rpcException = new RpcException("服务异常");
}
throw rpcException;
}
/**
* 校验resp
*
* @param t
* @param <T>
* @return
*/
private <T> RpcStatus checkResp(CallHandler<T> handler, T t) {
RpcStatus status = RpcStatus.SUCCESS;
try {
// 为空,或handlerCheck为false直接判断FAIL
if (t == null || !handler.check(t)) {
return RpcStatus.WARNING;
}
if (t instanceof Checker) {
status = ((Checker) t).check() ? RpcStatus.SUCCESS : RpcStatus.WARNING;
} else if (t instanceof List) {
// 为空认为不是理想结果
if (CollectionUtils.isEmpty((List) t)) {
status = RpcStatus.WARNING;
} else {
// 列表数据简单检测第一个元素
Object obj = ((List) t).get(0);
if (obj instanceof Checker) {
status = ((Checker) obj).check() ? RpcStatus.SUCCESS : RpcStatus.WARNING;
}
}
}
} catch (Exception e) {
LOG.error("collect error, msg={}", e.getMessage());
}
return status;
}
private String convertParam(Object param) {
if (param instanceof String) {
return (String) param;
}
String reqParam = "";
if (param instanceof Map) {
reqParam = EncodeUtil.encodeMap((Map) param);
} else if (param != null) {
reqParam = JSON.toJSONString(param);
}
return reqParam;
}
enum RpcStatus {
/**
* 成功
*/
SUCCESS(1),
/**
* 告警(请求成功,但非理想值)
*/
WARNING(2),
/**
* 异常
*/
EXCEPTION(3),
/**
* 超时
*/
TIMEOUT(4);
private final int value;
RpcStatus(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
enum Method {
/**
* Get请求
*/
GET,
/**
* Post表单请求
*/
POST,
/**
* 数据体(一般是post json)
*/
BODY
}
/**
* 模板调用
*/
@FunctionalInterface
public interface CallTemplate {
/**
* 模板调用类
*/
String executeCall();
}
/**
* 报文解析
*/
@FunctionalInterface
public interface CallHandler<T> {
/**
* 报文解析
*
* @param resp
* response body
*/
T handle(String resp) throws IOException;
/**
* 校验数据体
*
* @param t
* @return
*/
default boolean check(T t) {
return true;
}
}
}
package com.netease.mail.yanxuan.change.integration.client;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netease.mail.yanxuan.change.integration.rpc.RpcResultException;
import java.io.IOException;
public class SinoInfoRpcObjectData<T> implements RpcTemplate.CallHandler<T> {
private final Class<T> tClass;
public SinoInfoRpcObjectData(Class<T> tClass) {
this.tClass = tClass;
}
@Override
public T handle(String resp) throws IOException {
JSONObject rpcResult = JSON.parseObject(resp);
int code = rpcResult.getIntValue("code");
if (code == 200) {
return JSON.parseObject(rpcResult.getString("shareInfo"), tClass);
}
throw new RpcResultException("response error, code = " + code);
}
}
package com.netease.mail.yanxuan.change.integration.client;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.io.IOException;
public class SinoRpcObjectData<T> implements RpcTemplate.CallHandler<T> {
private final Class<T> tClass;
public SinoRpcObjectData(Class<T> tClass) {
this.tClass = tClass;
}
@Override
public T handle(String resp) throws IOException {
JSONObject rpcResult = JSON.parseObject(resp);
return JSON.parseObject(JSON.toJSONString(rpcResult), tClass);
}
}
package com.netease.mail.yanxuan.change.integration.client;
import org.apache.http.conn.ssl.TrustStrategy;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* 不校验,统统认为是可信的
*
* Created by leikun on 2017/5/7.
*/
public class TrustAnyStrategy implements TrustStrategy {
private static final TrustAnyStrategy INSTANCE = new TrustAnyStrategy();
public static TrustAnyStrategy get() {
return INSTANCE;
}
private TrustAnyStrategy() {}
@Override
public boolean isTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
return true;
}
}
...@@ -2,12 +2,15 @@ package com.netease.mail.yanxuan.change.integration.email.service.impl; ...@@ -2,12 +2,15 @@ package com.netease.mail.yanxuan.change.integration.email.service.impl;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.netease.mail.yanxuan.change.integration.client.RpcObjectData;
import com.netease.mail.yanxuan.change.integration.client.RpcTemplate;
import com.netease.mail.yanxuan.change.integration.email.service.UasClientService; import com.netease.mail.yanxuan.change.integration.email.service.UasClientService;
import com.netease.mail.yanxuan.change.integration.flow.email.EmailRpcService; import com.netease.mail.yanxuan.change.integration.flow.email.EmailRpcService;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
...@@ -26,23 +29,37 @@ public class UasClientServiceImpl implements UasClientService { ...@@ -26,23 +29,37 @@ public class UasClientServiceImpl implements UasClientService {
Logger logger = LoggerFactory.getLogger(UasClientServiceImpl.class); Logger logger = LoggerFactory.getLogger(UasClientServiceImpl.class);
private static final String TEST_URL = "http://127.0.0.1:8550/proxy/test.logistics-uas.service.mailsaas/push/email/qc";
private static final String ONLINE_URL = "http://127.0.0.1:8550/proxy/online.logistics-uas.service.mailsaas/push/email/qc";
@Autowired @Autowired
private EmailRpcService service; private EmailRpcService service;
@Value("${env:online}")
private String env;
@Autowired
private RpcTemplate rpcTemplate;
@Override @Override
public void sendEmail(String subject, String content, Collection<String> toList, Collection<String> ccList, List<File> fileList) { public void sendEmail(String subject, String content, Collection<String> toList, Collection<String> ccList, List<File> fileList) {
if (!CollectionUtils.isEmpty(toList)) { if (!CollectionUtils.isEmpty(toList)) {
Map<String, String> params = new HashMap(); String url = ONLINE_URL;
if ("test".equals(env)) {
url = TEST_URL;
}
Map<String, Object> params = new HashMap();
params.put("subject", subject);
params.put("content", content);
params.put("to", StringUtils.join(toList, ","));
params.put("topic", "qc");
if (!CollectionUtils.isEmpty(ccList)) { if (!CollectionUtils.isEmpty(ccList)) {
params.put("cc", StringUtils.join(ccList, ",")); params.put("cc", StringUtils.join(ccList, ","));
} }
logger.info(JSONObject.toJSONString("邮箱接口入参 subject={},content={},toList={},ccList={}"), subject, content, StringUtils.join(toList, ","), params.get("cc")); logger.info(JSONObject.toJSONString("邮箱接口入参 subject={},content={},toList={},ccList={}"), subject, content, StringUtils.join(toList, ","), params.get("cc"));
String res = service.sendEmail(subject, content, StringUtils.join(toList, ","), params.get("cc")); rpcTemplate.post(url, params, new RpcObjectData<>(String.class));
this.logger.info("[op:sendEmail] res={} ", res); //String res = service.sendEmail(subject, content, StringUtils.join(toList, ","), params.get("cc"));
JSONObject jsonObject = JSON.parseObject(res);
if (jsonObject.getInteger("code") != 200) {
this.logger.error("SendEmail", null, "send email failed, subject={},toList={},ccList={}", new Object[]{subject, JSON.toJSONString(toList), JSON.toJSONString(ccList)});
}
} }
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment