diff --git a/spring-boot-demo-alwaysuse/pom.xml b/spring-boot-demo-alwaysuse/pom.xml new file mode 100644 index 000000000..193fb1aa2 --- /dev/null +++ b/spring-boot-demo-alwaysuse/pom.xml @@ -0,0 +1,190 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.3.12.RELEASE + + + com.example + awaysuse + 0.0.1-SNAPSHOT + awaysuse + Demo project for Spring Boot + + 1.8 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.projectlombok + lombok + true + + + + org.springframework.boot + spring-boot-configuration-processor + true + + + + cn.hutool + hutool-all + 5.5.2 + + + com.alibaba + fastjson + 1.2.68 + compile + + + + uyun.whale + common-encryption + 2.0.4-SNAPSHOT + + + + com.squareup.okhttp + okhttp + 2.7.5 + + + + org.apache.commons + commons-lang3 + + + + + org.apache.poi + poi + 3.9 + + + org.apache.poi + poi-ooxml + 3.9 + + + org.apache.poi + poi-ooxml-schemas + 3.9 + + + + + org.elasticsearch + elasticsearch + 7.5.1 + + + + org.elasticsearch.client + elasticsearch-rest-high-level-client + 7.5.1 + + + org.elasticsearch + elasticsearch + + + org.elasticsearch.client + elasticsearch-rest-client + + + + + + org.elasticsearch.client + elasticsearch-rest-client + 7.5.1 + + + + commons-lang + commons-lang + 2.6 + + + + + org.apache.commons + commons-collections4 + 4.1 + + + + + + net.sf.ezmorph + ezmorph + 1.0.6 + + + + org.springframework.retry + spring-retry + + + + + org.aspectj + aspectjrt + 1.9.1 + + + org.aspectj + aspectjweaver + 1.9.1 + + + + org.apache.commons + commons-lang3 + + + + com.cronutils + cron-utils + 8.0.0 + + + + com.google.guava + guava + 28.1-jre + + + + com.hankcs + hanlp + portable-1.7.8 + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/AwaysuseApplication.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/AwaysuseApplication.java new file mode 100644 index 000000000..2850bf328 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/AwaysuseApplication.java @@ -0,0 +1,15 @@ +package com.example.awaysuse; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableScheduling; + +@SpringBootApplication +@EnableScheduling +public class AwaysuseApplication { + + public static void main(String[] args) { + SpringApplication.run(AwaysuseApplication.class, args); + } + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/callmsg/CallResultMsg.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/callmsg/CallResultMsg.java new file mode 100644 index 000000000..a1e863a83 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/callmsg/CallResultMsg.java @@ -0,0 +1,15 @@ +package com.example.awaysuse.callmsg; + +import com.example.awaysuse.result.ResultCode; +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class CallResultMsg { + private boolean result; + private int code; + private String message; + private T data; + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/callmsg/CodeAndMsg.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/callmsg/CodeAndMsg.java new file mode 100644 index 000000000..1d96b4bd3 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/callmsg/CodeAndMsg.java @@ -0,0 +1,24 @@ +package com.example.awaysuse.callmsg; + +import lombok.Data; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + + +@Getter +public enum CodeAndMsg{ + SUCCESS(1000, "SUCCESS"), + METHODFAIL(2000, "ENCOUNTER AN ERROR WHEN EXECUTE METHOD"), + NOT_FOUND(404, "Not Found"), + UNKNOWEXCEPTION(3000, "THIS IS AN UNKNOW EXCEPTION"), + BAD_GATEWAY(502, "Bad Gateway"); + + private int code; + private String msg; + + CodeAndMsg(int code, String msg){ + this.code = code; + this.msg = msg; + } +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/callmsg/UniformReponseHandler.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/callmsg/UniformReponseHandler.java new file mode 100644 index 000000000..bc0505e22 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/callmsg/UniformReponseHandler.java @@ -0,0 +1,47 @@ +package com.example.awaysuse.callmsg; + +import com.example.awaysuse.result.ResultCode; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +@RestControllerAdvice(annotations = RestController.class) +public class UniformReponseHandler { + + @ResponseStatus(HttpStatus.OK) + public CallResultMsg sendSuccessResponse(){ + return new CallResultMsg(true, CodeAndMsg.SUCCESS.getCode(), CodeAndMsg.SUCCESS.getMsg(), null); + } + + @ResponseStatus(HttpStatus.OK) + public CallResultMsg sendSuccessResponse(T data) { + return new CallResultMsg(true, CodeAndMsg.SUCCESS.getCode(), CodeAndMsg.SUCCESS.getMsg(), data); + } + + @ExceptionHandler(UserDefinedException.class) + @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) + public CallResultMsg sendErrorResponse_UserDefined(Exception exception){ + // return new CallResultMsg(false, ((UserDefinedException)exception).getException().getCode(), ((UserDefinedException)exception).getException().getMsg(), null); + return new CallResultMsg(false, HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.toString(), null); + + } + + + @ExceptionHandler(Exception.class) + @ResponseStatus(HttpStatus.BAD_GATEWAY) + public CallResultMsg badGatewayResponse(Exception exception){ + if (exception instanceof UserDefinedException) { + return this.sendErrorResponse_UserDefined(exception); + } + + return new CallResultMsg(false, CodeAndMsg.BAD_GATEWAY.getCode(),CodeAndMsg.BAD_GATEWAY.getMsg(),null); + } + + + @ResponseStatus(HttpStatus.NOT_FOUND) + public CallResultMsg notFoundErrorResponse_System(){ + return new CallResultMsg(false, CodeAndMsg.NOT_FOUND.getCode(),CodeAndMsg.NOT_FOUND.getMsg(),null); + } +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/callmsg/UserDefinedException.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/callmsg/UserDefinedException.java new file mode 100644 index 000000000..16c8a8eb7 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/callmsg/UserDefinedException.java @@ -0,0 +1,20 @@ +package com.example.awaysuse.callmsg; + +import com.example.awaysuse.result.ResultCode; + + +public class UserDefinedException extends RuntimeException { + private CodeAndMsg exception; + + public UserDefinedException(CodeAndMsg exception){ + this.exception = exception; + } + + public CodeAndMsg getException() { + return exception; + } + + public void setException(CodeAndMsg exception) { + this.exception = exception; + } +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/config/ESConfig.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/config/ESConfig.java new file mode 100644 index 000000000..250aea9e3 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/config/ESConfig.java @@ -0,0 +1,73 @@ +package com.example.awaysuse.config; + +import org.apache.http.HttpHost; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.CredentialsProvider; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.elasticsearch.client.RestClient; +import org.elasticsearch.client.RestClientBuilder; +import org.elasticsearch.client.RestHighLevelClient; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.ArrayList; +import java.util.List; + +/** + * @auther: fengh + * @Date: 2020/7/2 17:04 + * @Description: + */ +@Configuration +public class ESConfig { + + @Value("${elasticsearch.hosts}") + private String hosts; + @Value("${elasticsearch.username}") + private String username; + @Value("${elasticsearch.passowrd}") + private String password; + @Value("${elasticsearch.schema}") + private String schema; + @Value("${elasticsearch.connectTimeOut}") + private int connectTimeOut; + @Value("${elasticsearch.socketTimeOut}") + private int socketTimeOut; + @Value("${elasticsearch.connectionRequestTimeOut}") + private int connectionRequestTimeOut; + @Value("${elasticsearch.maxConnectNum}") + private int maxConnectNum; + @Value("${elasticsearch.maxConnectPerRoute}") + private int maxConnectPerRoute; + + @Bean("restHighLevelClient") + public RestHighLevelClient client(){ + CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); + credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); + List hostList = new ArrayList<>(); + String[] hostArray = hosts.split(","); + for (String host : hostArray) { + String[] ipPort = host.split(":"); + hostList.add(new HttpHost(ipPort[0], Integer.parseInt(ipPort[1]), schema)); + } + RestClientBuilder builder = RestClient.builder(hostList.toArray(new HttpHost[0])); + // 异步httpclient连接延时配置 + builder.setRequestConfigCallback(requestConfigBuilder -> { + requestConfigBuilder.setConnectTimeout(connectTimeOut); + requestConfigBuilder.setSocketTimeout(socketTimeOut); + requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeOut); + return requestConfigBuilder; + }); + // 异步httpclient连接数配置 + builder.setHttpClientConfigCallback(httpClientBuilder -> { + httpClientBuilder.setMaxConnTotal(maxConnectNum); + httpClientBuilder.setMaxConnPerRoute(maxConnectPerRoute); + httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); + return httpClientBuilder; + }); + return new RestHighLevelClient(builder); + } + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/config/GlobalExceptionHandler.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/config/GlobalExceptionHandler.java new file mode 100644 index 000000000..558afa63a --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/config/GlobalExceptionHandler.java @@ -0,0 +1,78 @@ +package com.example.awaysuse.config; + +import com.example.awaysuse.response.ResponseResult; +import org.springframework.http.HttpStatus; +import org.springframework.web.HttpMediaTypeNotSupportedException; +import org.springframework.web.HttpRequestMethodNotSupportedException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.client.HttpServerErrorException; +import org.springframework.web.servlet.NoHandlerFoundException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.List; +import java.util.stream.Collectors; + +/** + * @Author fengh + * @Date 2020/9/14 15:51 + * @Description 全局统一异常处理类 + */ +@RestControllerAdvice +public class GlobalExceptionHandler { + + /** + * 404异常处理 + */ + @ExceptionHandler(value = NoHandlerFoundException.class) + @ResponseStatus(HttpStatus.NOT_FOUND) + public ResponseResult errorHandler(HttpServletRequest request, NoHandlerFoundException exception, HttpServletResponse response) { + return ResponseResult.error(HttpStatus.NOT_FOUND.value(), exception.getMessage()); + } + + /** + * 405异常处理 + */ + @ExceptionHandler(HttpRequestMethodNotSupportedException.class) + public ResponseResult errorHandler(HttpServletRequest request, HttpRequestMethodNotSupportedException exception, HttpServletResponse response) { + return ResponseResult.error(HttpStatus.METHOD_NOT_ALLOWED.value(), exception.getMessage()); + } + + /** + * 415异常处理 + */ + @ExceptionHandler(HttpMediaTypeNotSupportedException.class) + public ResponseResult errorHandler(HttpServletRequest request, HttpMediaTypeNotSupportedException exception, HttpServletResponse response) { + return ResponseResult.error(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value(), exception.getMessage()); + } + + /** + * 500异常处理 + */ + @ExceptionHandler(HttpServerErrorException.class) + public ResponseResult errorHandler(HttpServletRequest request, HttpServerErrorException exception, HttpServletResponse response) { + return ResponseResult.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), exception.getMessage()); + } + + /** + * 参数校验错误处理 + */ + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseResult errorHandler(HttpServletRequest request, MethodArgumentNotValidException exception, HttpServletResponse response) { + List errors = exception.getBindingResult().getAllErrors().stream().map(error -> error.getDefaultMessage()).collect(Collectors.toList()); + return ResponseResult.error(0, String.join(",", errors)); + } + + /** + * 普通异常处理 + */ + @ExceptionHandler(Exception.class) + public ResponseResult errorHandler(HttpServletRequest request, Exception exception, HttpServletResponse response) { + return ResponseResult.error(0, exception.getMessage()); + } + + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/config/IndexConfig.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/config/IndexConfig.java new file mode 100644 index 000000000..84aabc9d1 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/config/IndexConfig.java @@ -0,0 +1,16 @@ +package com.example.awaysuse.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +import java.util.Map; + +@Component +@Data +@ConfigurationProperties(prefix="custom") +public class IndexConfig { + + private Map index; + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/controller/ControllerResponseAdvice.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/controller/ControllerResponseAdvice.java new file mode 100644 index 000000000..1299cdd6c --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/controller/ControllerResponseAdvice.java @@ -0,0 +1,38 @@ +package com.example.awaysuse.controller; + +import com.example.awaysuse.result.ResultCode; +import com.example.awaysuse.result.ResultVo; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.core.MethodParameter; +import org.springframework.http.MediaType; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.server.ServerHttpRequest; +import org.springframework.http.server.ServerHttpResponse; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; + +//@RestControllerAdvice(basePackages = {"com.bugpool.leilema"}) +public class ControllerResponseAdvice implements ResponseBodyAdvice { + @Override + public boolean supports(MethodParameter methodParameter, Class> aClass) { + // response是ResultVo类型,或者注释了NotControllerResponseAdvice都不进行包装 + return !methodParameter.getParameterType().isAssignableFrom(ResultVo.class); + } + + @Override + public Object beforeBodyWrite(Object data, MethodParameter returnType, MediaType mediaType, Class> aClass, ServerHttpRequest request, ServerHttpResponse response) { + // String类型不能直接包装 + if (returnType.getGenericParameterType().equals(String.class)) { + ObjectMapper objectMapper = new ObjectMapper(); + try { + // 将数据包装在ResultVo里后转换为json串进行返回 + return objectMapper.writeValueAsString(new ResultVo(data)); + } catch (JsonProcessingException e) { + // throw new APIException(ResultCode.RESPONSE_PACK_ERROR, e.getMessage()); + } + } + // 否则直接包装成ResultVo返回 + return new ResultVo(data); + } +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/controller/GetInfoController.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/controller/GetInfoController.java new file mode 100644 index 000000000..e69de29bb diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/controller/TestCallMsgResult.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/controller/TestCallMsgResult.java new file mode 100644 index 000000000..e9974093e --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/controller/TestCallMsgResult.java @@ -0,0 +1,45 @@ +package com.example.awaysuse.controller; + + +import com.example.awaysuse.callmsg.CallResultMsg; +import com.example.awaysuse.callmsg.CodeAndMsg; +import com.example.awaysuse.callmsg.UniformReponseHandler; +import com.example.awaysuse.callmsg.UserDefinedException; +import com.sun.org.apache.regexp.internal.RE; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +import java.util.HashMap; +import java.util.Map; + +// 测试封装返回的结果集 +@RestController +public class TestCallMsgResult { + + @GetMapping("/doTestObject") + public CallResultMsg testObjectReturn() { + Map map = new HashMap(); + map.put("qingfen", 16); + map.put("lantian", 17); + map.put("baiyun", 18); + CallResultMsg callResultMsg = new UniformReponseHandler().sendSuccessResponse(map); + System.out.println(CodeAndMsg.SUCCESS); + return callResultMsg; + } + + + @GetMapping("/doTestException/{x}") + public int testExceptionResturn(@PathVariable int x) { + /*if (0 < x && x < 10) { + // throw new UserDefinedException(CodeAndMsg.METHODFAIL); + throw new UserDefinedException(CodeAndMsg.METHODFAIL); + } else { + return 1 / 0; + }*/ + return 1/0; + } + + + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/controller/UserInfoController.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/controller/UserInfoController.java new file mode 100644 index 000000000..e0a82451f --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/controller/UserInfoController.java @@ -0,0 +1,34 @@ +package com.example.awaysuse.controller; + +import com.example.awaysuse.model.UserInfoEntity; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +@RestController +@RequiredArgsConstructor +@Slf4j +public class UserInfoController { + + final UserInfoEntity userInfo; + + @RequestMapping("getUser") + public String getUserInfo(){ + log.info(userInfo.getName()); + int i=2; + return userInfo.getName(); + } + + public static void main(String args[]) { + String str = "fengxb@163.com"; + String pattern = "\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\.)+[A-Za-z]{2,14}"; + Pattern r = Pattern.compile(pattern); + Matcher m = r.matcher(str); + System.out.println("正则"+m.matches()); + } + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/exception/MyNotFoundException.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/exception/MyNotFoundException.java new file mode 100644 index 000000000..7fd659b43 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/exception/MyNotFoundException.java @@ -0,0 +1,50 @@ +package com.example.awaysuse.exception; + +import com.example.awaysuse.callmsg.CallResultMsg; +import com.example.awaysuse.callmsg.UniformReponseHandler; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.catalina.util.RequestUtil; +import org.apache.poi.ss.formula.functions.T; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.web.ErrorProperties; +import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController; +import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver; +import org.springframework.boot.web.servlet.error.ErrorAttributes; +import org.springframework.boot.web.servlet.error.ErrorController; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.servlet.ModelAndView; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @Author: + * @Date: 2020/7/30 18:26 + * @Description: + */ + +@Controller +public class MyNotFoundException implements ErrorController { + + @Override + public String getErrorPath() { + return "/error"; + } + + @RequestMapping(value = "/error") + @ResponseBody + public CallResultMsg getError() { + return new UniformReponseHandler().notFoundErrorResponse_System(); + } + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/model/Doc.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/model/Doc.java new file mode 100644 index 000000000..7ddda124c --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/model/Doc.java @@ -0,0 +1,29 @@ +package com.example.awaysuse.model; + +import java.util.HashMap; +import java.util.Map; + +/** + * ES查询结果封装类 + * @author + */ +public class Doc extends HashMap { + private static final long serialVersionUID = 4978196894185418504L; + + public Doc(){ + + } + + public Doc(Map map){ + this.putAll(map); + } + + public static Doc put(Map map){ + return new Doc(map); + } + + public Doc build(){ + return this; + } + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/model/Help.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/model/Help.java new file mode 100644 index 000000000..8b58397c2 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/model/Help.java @@ -0,0 +1,27 @@ +package com.example.awaysuse.model; + +import lombok.*; + +import java.io.Serializable; + + +public class Help implements Serializable { + + int userId; + + public Help setUserId(int uid) { + this.userId = uid; + return this; + } + + public int getUserId() { + return userId; + } + + @Override + public String toString() { + return "Help{" + + "userId=" + userId + + '}'; + } +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/model/PageData.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/model/PageData.java new file mode 100644 index 000000000..441a841c8 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/model/PageData.java @@ -0,0 +1,51 @@ +package com.example.awaysuse.model; + +import lombok.Data; + +/** + * @Author: + * @Date: + * @Description: + */ +@Data +public class PageData { + /** + * 当前页面 + */ + private int pageNum; + + /** + * 每页数量 + */ + private int pageSize; + + /** + * 记录总数 + */ + private long totalCount; + + /** + * 页码总数 + */ + private int totalPages; + + /** + * 分页数据 + */ + private T data; + + public PageData() { + } + + public PageData(T data) { + this.data = data; + } + + public PageData(int pageNum, int pageSize, long totalCount, int totalPage, T data) { + this.pageNum = pageNum; + this.pageSize = pageSize; + this.totalCount = totalCount; + this.totalPages = totalPage; + this.data = data; + } +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/model/Person.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/model/Person.java new file mode 100644 index 000000000..28c7b3d68 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/model/Person.java @@ -0,0 +1,56 @@ +package com.example.awaysuse.model; + +import lombok.*; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.Date; + +/** + * Person + * + * @author fxbin + * @version v1.0 + * @since 2019/9/15 23:04 + */ +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Accessors(chain = true) +@ToString +public class Person implements Serializable { + + private static final long serialVersionUID = 8510634155374943623L; + + /** + * 主键 + */ + private Long id; + + /** + * 名字 + */ + private String name; + + /** + * 国家 + */ + private String country; + + /** + * 年龄 + */ + private Integer age; + + /** + * 生日 + */ + private Date birthday; + + /** + * 介绍 + */ + private String remark; + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/model/ProductInfo.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/model/ProductInfo.java new file mode 100644 index 000000000..3c95d5645 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/model/ProductInfo.java @@ -0,0 +1,9 @@ +package com.example.awaysuse.model; + + + +public class ProductInfo { + + + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/model/ReportTimeLimit.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/model/ReportTimeLimit.java new file mode 100644 index 000000000..eed4fbaf0 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/model/ReportTimeLimit.java @@ -0,0 +1,29 @@ +package com.example.awaysuse.model; + +public class ReportTimeLimit { + + /** + * 当前时间上限 + */ + long currentUpper; + /** + * 当前时间下限 + */ + long currentLower; + /** + * 环比上限 + */ + long momUpper; + /** + * 环比下限 + */ + long momLower; + /** + * 同比上限 + */ + long yoyUpper; + /** + * 同比下限 + */ + long yoyLower; +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/model/UserInfoEntity.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/model/UserInfoEntity.java new file mode 100644 index 000000000..8b24fab80 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/model/UserInfoEntity.java @@ -0,0 +1,28 @@ +package com.example.awaysuse.model; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +/** + *

+ * 开发人员配置信息 + *

+ * + * @package: com.xkcoding.properties.property + * @description: 开发人员配置信息 + * @author: yangkai.shen + * @date: Created in 2018/9/29 10:51 AM + * @copyright: Copyright (c) 2018 + * @version: V1.0 + * @modified: yangkai.shen + */ +@Data +@ConfigurationProperties(prefix = "userinfo") +@Component +public class UserInfoEntity { + private String name; + private String website; + private String qq; + private String phoneNumber; +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/model/vo/ProductInfoVo.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/model/vo/ProductInfoVo.java new file mode 100644 index 000000000..cc609e113 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/model/vo/ProductInfoVo.java @@ -0,0 +1,21 @@ +package com.example.awaysuse.model.vo; + + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class ProductInfoVo { + // 商品名称 + private String productName; + + // 商品价格 + private BigDecimal productPrice; + + // 上架状态 + private Integer productStatus; + + + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/myrequest/RequestDemoController1.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/myrequest/RequestDemoController1.java new file mode 100644 index 000000000..9af3a8933 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/myrequest/RequestDemoController1.java @@ -0,0 +1,62 @@ +package com.example.awaysuse.myrequest; + + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.client.RestTemplate; + +import javax.servlet.http.HttpServletRequest; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Set; + +@RestController +public class RequestDemoController1 { + + // @Autowired + //private RestTemplate restTemplate; + + + + @GetMapping("/getParams") + public String getParams(String a,int b) { + return "get success"; + } + + + @PostMapping("/postTest") + public String postTest(HttpServletRequest request) { + String age1 = request.getParameter("age"); + String name1 = request.getParameter("name"); + System.out.println("age1=" + age1 + ",name1=" + name1); + + new Thread(new Runnable() { + @Override + public void run() { + String age2 = request.getParameter("age"); + String name2 = request.getParameter("name"); + System.out.println("age2=" + age2 + ",name2=" + name2); + //模拟业务请求 + try { + Thread.sleep(200); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + age2 = request.getParameter("age"); + name2 = request.getParameter("name"); + System.out.println("age2=" + age2 + ",name2=" + name2); + } + }).start(); + return "post success"; + } + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/myrequest/RequestDemoController2.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/myrequest/RequestDemoController2.java new file mode 100644 index 000000000..211989f3a --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/myrequest/RequestDemoController2.java @@ -0,0 +1,13 @@ +package com.example.awaysuse.myrequest; + + +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletRequest; + +@RestController +public class RequestDemoController2 { + + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/response/ResponseResult.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/response/ResponseResult.java new file mode 100644 index 000000000..090058b4a --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/response/ResponseResult.java @@ -0,0 +1,51 @@ +package com.example.awaysuse.response; + +import lombok.Data; + +/** + * @Author feng + * @Date 2020/9/10 17:01 + * @Description + */ +@Data +public class ResponseResult { + + private Integer code = 200; + private String message = "success"; + private T data; + + public ResponseResult(){ + + } + + public ResponseResult(T data){ + this.data = data; + } + + public ResponseResult(int code, String message){ + this.code = code; + this.message = message; + } + + public ResponseResult(String message, T data){ + this.message = message; + this.data = data; + } + + public static ResponseResult success(){ + return new ResponseResult(); + } + + public static ResponseResult success(T data){ + return new ResponseResult(data); + } + + public static ResponseResult success(String message, T data){ + return new ResponseResult(message, data); + } + + public static ResponseResult error(int code, String message){ + return new ResponseResult(code, message); + } + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/result/ResultCode.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/result/ResultCode.java new file mode 100644 index 000000000..21a6a8d90 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/result/ResultCode.java @@ -0,0 +1,25 @@ +package com.example.awaysuse.result; + +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Getter +@NoArgsConstructor +public enum ResultCode implements StatusCode{ + + SUCCESS(1000, "请求成功"), + FAILED(1001, "请求失败"), + VALIDATE_ERROR(1002, "参数校验失败"), + RESPONSE_PACK_ERROR(1003, "response返回包装失败"); + + + private int code; + private String msg; + + ResultCode(int code, String msg) { + this.code = code; + this.msg = msg; + } + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/result/ResultVo.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/result/ResultVo.java new file mode 100644 index 000000000..c616e5176 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/result/ResultVo.java @@ -0,0 +1,45 @@ +package com.example.awaysuse.result; + +import lombok.Data; + + +@Data +public class ResultVo { + + // 状态码 + private int code; + + // 状态信息 + private String msg; + + // 返回对象 + private Object data; + + // 手动设置返回vo + public ResultVo(int code, Object data, String msg) { + this.code = code; + this.msg = msg; + this.data = data; + } + + // 默认返回成功状态码,数据对象 + public ResultVo(Object data) { + this.code = ResultCode.SUCCESS.getCode(); + this.msg = ResultCode.SUCCESS.getMsg(); + this.data = data; + } + + // 返回指定状态码,数据对象 + public ResultVo(StatusCode statusCode, Object data) { + this.code = statusCode.getCode(); + this.msg = statusCode.getMsg(); + this.data = data; + } + + // 只返回状态码 + public ResultVo(StatusCode statusCode) { + this.code = statusCode.getCode(); + this.msg = statusCode.getMsg(); + this.data = null; + } +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/result/StatusCode.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/result/StatusCode.java new file mode 100644 index 000000000..23a13b72b --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/result/StatusCode.java @@ -0,0 +1,9 @@ +package com.example.awaysuse.result; + + +public interface StatusCode { + + public int getCode(); + public String getMsg(); + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/service/BranchHandle.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/service/BranchHandle.java new file mode 100644 index 000000000..aaef68083 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/service/BranchHandle.java @@ -0,0 +1,11 @@ +package com.example.awaysuse.service; + +@FunctionalInterface +public interface BranchHandle { + + void trueOrFalseHandle(Runnable trueHandle, Runnable falseHandle); + + + + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/service/PresentOrElseHandler.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/service/PresentOrElseHandler.java new file mode 100644 index 000000000..fd9979c28 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/service/PresentOrElseHandler.java @@ -0,0 +1,17 @@ +package com.example.awaysuse.service; + +import java.util.function.Consumer; + +public interface PresentOrElseHandler { + + /** + * 值不为空时执行消费操作 + * 值为空时执行其他的操作 + * + * @param action 值不为空时,执行的消费操作 + * @param emptyAction 值为空时,执行的操作 + * @return void + **/ + void presentOrElseHandle(Consumer action, Runnable emptyAction); + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/service/ThrowExceptionFunction.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/service/ThrowExceptionFunction.java new file mode 100644 index 000000000..fb1ed57aa --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/service/ThrowExceptionFunction.java @@ -0,0 +1,8 @@ +package com.example.awaysuse.service; + +@FunctionalInterface +public interface ThrowExceptionFunction { + + void throwMessage(String message); + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/thread/MyTask.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/thread/MyTask.java new file mode 100644 index 000000000..dddc9b812 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/thread/MyTask.java @@ -0,0 +1,30 @@ +package com.example.awaysuse.thread; + +public class MyTask implements Runnable{ + private int id; + //由于run方法是重写接口中的方法,因此id这个属性初始化可以利用构造方法完成 + + public MyTask(int id) { + this.id = id; + } + + @Override + public void run() { + String name = Thread.currentThread().getName(); + System.out.println("线程:"+name+" 即将执行任务:"+id); + try { + Thread.sleep(200); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println("线程:"+name+" 完成了任务:"+id); + } + + @Override + public String toString() { + return "MyTask{" + + "id=" + id + + '}'; + } + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/thread/MyTest.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/thread/MyTest.java new file mode 100644 index 000000000..94bf1b39b --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/thread/MyTest.java @@ -0,0 +1,40 @@ +package com.example.awaysuse.thread; + + +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +public class MyTest { + public static void main(String[] args) { + //1:创建线程池类对象; + /* MyThreadPool pool = new MyThreadPool(2, 4, 20); + //2: 提交多个任务 + for (int i = 0; i < 30; i++) { + //3:创建任务对象,并提交给线程池 + MyTask my = new MyTask(i); + pool.submit(my); + }*/ + + ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); + /*executorService.scheduleAtFixedRate(()->{ + try { + //加上这个,看看1没执行完,会不会马上执行2,意即会不会开个新线程去执行 + Thread.sleep(1000); + }catch (Exception ex){ + + } + System.out.println(Thread.currentThread().getName()+" run : "+ System.currentTimeMillis()); + }, 0, 100, TimeUnit.MILLISECONDS);*/ + //0延时,每隔100毫秒执行一次 + executorService.schedule(new Runnable() { + @Override + public void run() { + System.out.println("俩人相视一笑~ 嘿嘿嘿"); + } + }, 10, TimeUnit.SECONDS); + } + + + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/thread/MyThreadPool.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/thread/MyThreadPool.java new file mode 100644 index 000000000..50f822756 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/thread/MyThreadPool.java @@ -0,0 +1,53 @@ +package com.example.awaysuse.thread; + +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +public class MyThreadPool { + + // 1:任务队列 集合 需要控制线程安全问题 + private List tasks = Collections.synchronizedList(new LinkedList<>()); + //2:当前线程数量 + private int num; + //3:核心线程数量 + private int corePoolSize; + //4:最大线程数量 + private int maxSize; + //5:任务队列的长度 + private int workSize; + + public MyThreadPool(int corePoolSize, int maxSize, int workSize) { + this.corePoolSize = corePoolSize; + this.maxSize = maxSize; + this.workSize = workSize; + } + + //1:提交任务; + public void submit(Runnable r){ + //判断当前集合中任务的数量,是否超出了最大任务数量 + if(tasks.size()>=workSize){ + System.out.println("任务:"+r+"被丢弃了..."); + }else { + tasks.add(r); + //执行任务 + execTask(r); + } + } + //2:执行任务; + private void execTask(Runnable r) { + //判断当前线程池中的线程总数量,是否超出了核心数, + if(num < corePoolSize){ + new MyWorker("核心线程:"+num,tasks).start(); + num++; + }else if(num < maxSize){ + new MyWorker("非核心线程:"+num,tasks).start(); + num++; + }else { + System.out.println("任务:"+r+" 被缓存了..."); + } + } + + + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/thread/MyWorker.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/thread/MyWorker.java new file mode 100644 index 000000000..e2ba27467 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/thread/MyWorker.java @@ -0,0 +1,26 @@ +package com.example.awaysuse.thread; + +import java.util.List; + +public class MyWorker extends Thread{ + + + private String name;//保存线程的名字 + private List tasks; + //利用构造方法,给成员变量赋值 + + public MyWorker(String name, List tasks) { + super(name); + this.tasks = tasks; + } + + @Override + public void run() { + //判断集合中是否有任务,只要有,就一直执行任务 + while (tasks.size()>0){ + Runnable r = tasks.remove(0); + r.run(); + } + } + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/BeanConvertUtils.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/BeanConvertUtils.java new file mode 100644 index 000000000..711be3a67 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/BeanConvertUtils.java @@ -0,0 +1,79 @@ +package com.example.awaysuse.util; + +import org.springframework.beans.BeanUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Supplier; + +public class BeanConvertUtils extends BeanUtils { + + public static T convertTo(S source, Supplier targetSupplier) { + return convertTo(source, targetSupplier, null); + } + + /** + * 转换对象 + * + * @param source 源对象 + * @param targetSupplier 目标对象供应方 + * @param callBack 回调方法 + * @param 源对象类型 + * @param 目标对象类型 + * @return 目标对象 + */ + public static T convertTo(S source, Supplier targetSupplier, ConvertCallBack callBack) { + if (null == source || null == targetSupplier) { + return null; + } + + T target = targetSupplier.get(); + copyProperties(source, target); + if (callBack != null) { + callBack.callBack(source, target); + } + return target; + } + + public static List convertListTo(List sources, Supplier targetSupplier) { + return convertListTo(sources, targetSupplier, null); + } + + /** + * 转换对象 + * + * @param sources 源对象list + * @param targetSupplier 目标对象供应方 + * @param callBack 回调方法 + * @param 源对象类型 + * @param 目标对象类型 + * @return 目标对象list + */ + public static List convertListTo(List sources, Supplier targetSupplier, ConvertCallBack callBack) { + if (null == sources || null == targetSupplier) { + return null; + } + + List list = new ArrayList<>(sources.size()); + for (S source : sources) { + T target = targetSupplier.get(); + copyProperties(source, target); + if (callBack != null) { + callBack.callBack(source, target); + } + list.add(target); + } + return list; + } + + /** + * 回调接口 + * + * @param 源对象类型 + * @param 目标对象类型 + */ + @FunctionalInterface + public interface ConvertCallBack { + void callBack(S t, T s); + } +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/BigDecimalUtils.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/BigDecimalUtils.java new file mode 100644 index 000000000..47fa7cb33 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/BigDecimalUtils.java @@ -0,0 +1,80 @@ +package com.example.awaysuse.util; + +import java.math.BigDecimal; + +/** + * @Author shuaige + * @Date 2022/4/17 + * @Version 1.0 + **/ +public class BigDecimalUtils { + // 加法 + public static BigDecimal doubleAdd(double v1, double v2) { + BigDecimal b1 = new BigDecimal(Double.toString(v1)); + BigDecimal b2 = new BigDecimal(Double.toString(v2)); + return b1.add(b2); + } + public static BigDecimal floatAdd(float v1, float v2) { + BigDecimal b1 = new BigDecimal(Float.toString(v1)); + BigDecimal b2 = new BigDecimal(Float.toString(v2)); + return b1.add(b2); + } + // 减法 + public static BigDecimal doubleSub(double v1, double v2) { + BigDecimal b1 = new BigDecimal(Double.toString(v1)); + BigDecimal b2 = new BigDecimal(Double.toString(v2)); + return b1.subtract(b2); + } + public static BigDecimal floatSub(float v1, float v2) { + BigDecimal b1 = new BigDecimal(Float.toString(v1)); + BigDecimal b2 = new BigDecimal(Float.toString(v2)); + return b1.subtract(b2); + } + // 乘法 + public static BigDecimal doubleMul(double v1, double v2) { + BigDecimal b1 = new BigDecimal(Double.toString(v1)); + BigDecimal b2 = new BigDecimal(Double.toString(v2)); + return b1.multiply(b2); + } + public static BigDecimal floatMul(float v1, float v2) { + BigDecimal b1 = new BigDecimal(Float.toString(v1)); + BigDecimal b2 = new BigDecimal(Float.toString(v2)); + return b1.multiply(b2); + } + // 除法 + public static BigDecimal doubleDiv(double v1, double v2) { + BigDecimal b1 = new BigDecimal(Double.toString(v1)); + BigDecimal b2 = new BigDecimal(Double.toString(v2)); + // 保留小数点后两位 ROUND_HALF_UP = 四舍五入 + return b1.divide(b2, 2, BigDecimal.ROUND_HALF_UP); + } + public static BigDecimal floatDiv(float v1, float v2) { + BigDecimal b1 = new BigDecimal(Float.toString(v1)); + BigDecimal b2 = new BigDecimal(Float.toString(v2)); + // 保留小数点后两位 ROUND_HALF_UP = 四舍五入 + return b1.divide(b2, 2, BigDecimal.ROUND_HALF_UP); + } + /** + * 比较v1 v2大小 + * @param v1 + * @param v2 + * @return v1>v2 return 1 v1=v2 return 0 v1 + * 基于concurrentHash的本地缓存工具类 + * 缓存删除基于timer定时器 + *
+ * @author hejianfeng
+ * @date 2019/10/5
+ * @param
+ * @return
+ * 
+ * 修改记录
+ * 版本号      修订日期        修改人     bug编号       修改内容
+ * 1.0.0      2019/10/5      hejianfeng                      新建
+ * 
+ */ +@Component +public class CacheUtil { + + //默认大小 + private static final int DEFAULT_CAPACITY = 1024; + + // 最大缓存大小 + private static final int MAX_CAPACITY = 10000; + + //默认缓存过期时间 + private static final long DEFAULT_TIMEOUT = 3600; + + //1000毫秒 + private static final long SECOND_TIME = 1000; + + //存储缓存的Map + private static final ConcurrentHashMap map; + + private static final Timer timer; + + static { + map = new ConcurrentHashMap<>(DEFAULT_CAPACITY); + timer = new Timer(); + } + + //私有化构造方法 + private CacheUtil() { + + } + + /** + *
+     *     缓存任务清除类
+     * 
+     * @author hejianfeng
+     * @date 2019/10/5
+     * @param
+     * @return
+     * 
+     * 修改记录
+     * 版本号      修订日期        修改人     bug编号       修改内容
+     * 1.0.0      2019/10/5      hejianfeng                      新建
+     * 
+ */ + static class ClearTask extends TimerTask { + private String key; + + public ClearTask(String key) { + this.key = key; + } + + @Override + public void run() { + CacheUtil.remove(key); + } + + } + + //==================缓存的增删改查 + + /** + *
+     *     添加缓存
+     * 
+     * @author hejianfeng
+     * @date 2019/10/5
+     * @param
+     * @param
+     * @return void
+     * 
+     * 修改记录
+     * 版本号      修订日期        修改人     bug编号       修改内容
+     * 1.0.0      2019/10/5      hejianfeng                      新建
+     * 
+ */ + public boolean put(String key,Object object) { + if (checkCapacity()) { + /* String res = HttpUtils.doGet(uyun_alert_url, null); + JSONObject jsonObject=JSONObject.parseObject(res); + JSONArray recordsArray = jsonObject.getJSONArray("records"); + Map alertMap=recordsArray.stream().collect(Collectors.toMap(item ->((JSONObject)item).getString("name"), Function.identity(), (item, item1) -> item)); +*/ + + //默认缓存时间 + timer.schedule(new ClearTask(key), DEFAULT_TIMEOUT); + return true; + } + return false; + } + + /** + *
+     *     添加缓存
+     * 
+     * @author hejianfeng
+     * @date 2019/10/5
+     * @param key
+     * @param object
+     * @param time_out  :缓存过期时间:单位秒
+     * @return void
+     * 
+     * 修改记录
+     * 版本号      修订日期        修改人     bug编号       修改内容
+     * 1.0.0      2019/10/5      hejianfeng                      新建
+     * 
+ */ + public static boolean put(String key, Object object, int time_out) { + if (checkCapacity()) { + map.put(key, object); + //默认缓存时间 + timer.schedule(new ClearTask(key), time_out * SECOND_TIME); + } + return false; + } + + + /** + *
+     *     判断容量大小
+     * 
+     * @author hejianfeng
+     * @date 2019/10/5
+     * @param
+     * @return boolean
+     * 
+     * 修改记录
+     * 版本号      修订日期        修改人     bug编号       修改内容
+     * 1.0.0      2019/10/5      hejianfeng                      新建
+     * 
+ */ + public static boolean checkCapacity() { + return map.size() < MAX_CAPACITY; + } + + /** + *
+     *     批量增加缓存
+     * 
+     * @author hejianfeng
+     * @date 2019/10/5
+     * @param m
+     * @param time_out
+     * @return void
+     * 
+     * 修改记录
+     * 版本号      修订日期        修改人     bug编号       修改内容
+     * 1.0.0      2019/10/5      hejianfeng                      新建
+     * 
+ */ + public static boolean put(Map m, int time_out) { + if (map.size() + m.size() <= MAX_CAPACITY) { + map.putAll(map); + for (String key : m.keySet()) { + timer.schedule(new ClearTask(key), time_out * SECOND_TIME); + } + return true; + } + return false; + } + + /** + *
+     *     删除缓存
+     * 
+     * @author hejianfeng
+     * @date 2019/10/5
+     * @param key
+     * @return void
+     * 
+     * 修改记录
+     * 版本号      修订日期        修改人     bug编号       修改内容
+     * 1.0.0      2019/10/5      hejianfeng                      新建
+     * 
+ */ + public static void remove(String key) { + map.remove(key); + } + + /** + *
+     *     清除所有缓存
+     * 
+     * @author hejianfeng
+     * @date 2019/10/5
+     * @param
+     * @return void
+     * 
+     * 修改记录
+     * 版本号      修订日期        修改人     bug编号       修改内容
+     * 1.0.0      2019/10/5      hejianfeng                      新建
+     * 
+ */ + public void clearAll() { + if (map.size() > 0) { + map.clear(); + } + timer.cancel(); + } + + /** + *
+     *     获取缓存
+     * 
+     * @author hejianfeng
+     * @date 2019/10/5
+     * @param key
+     * @return java.lang.Object
+     * 
+     * 修改记录
+     * 版本号      修订日期        修改人     bug编号       修改内容
+     * 1.0.0      2019/10/5      hejianfeng                      新建
+     * 
+ */ + public static Object get(String key) { + return map.get(key); + } + + /** + *
+     *     是否包含某个缓存
+     * 
+     * @author hejianfeng
+     * @date 2019/10/5
+     * @param key
+     * @return boolean
+     * 
+     * 修改记录
+     * 版本号      修订日期        修改人     bug编号       修改内容
+     * 1.0.0      2019/10/5      hejianfeng                      新建
+     * 
+ */ + public static boolean isContain(String key) { + return map.contains(key); + } + + + public static void main(String[] args) { + /* Map mp=new HashMap<>(); + mp.put("应用",0); + mp.put("中间件",0); + mp.put("数据库",0); + mp.put("服务器",0); + mp.put("网络设备",0); + mp.put("全流程",0); + mp.put("云管",0); + mp.put("alertTotal",0); + mp.put("安全事件",0); + map.put("alertInfo", mp); + CacheUtil.put("alertInfo",mp,20);*/ + + + + Object alertInfo = CacheUtil.get("alertInfo"); + System.out.println(alertInfo); + + } + + + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/CommonUtils.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/CommonUtils.java new file mode 100644 index 000000000..01cdd0611 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/CommonUtils.java @@ -0,0 +1,54 @@ +package com.example.awaysuse.util; + +import java.math.BigDecimal; + +/** + * Created by clt on 2020/3/12. + * 数据的基本算法 + */ +public class CommonUtils { + public static Boolean isNull(Object str) { + if(null==str||str.toString().trim().equals("")||str.toString().trim().equals("null")){ + return true; + } + return false; + } + public static Double calcRate(Integer coActualNum, Integer coTdNum) { + if (coActualNum != null && coTdNum != null && coTdNum != 0 ) { + return 1.0 * coActualNum / coTdNum; + } else if (coTdNum == null || coTdNum == 0) { + return 0.0; + } else { + return 0.0; + } + } + + public static String isNullOrStr(Object c_siteopf_id) { + if (c_siteopf_id==null){ + return ""; + } + return c_siteopf_id.toString().trim(); + } + public static Integer isNullOrInter(Object c_siteopf_id) { + if (c_siteopf_id==null){ + return 0; + } + return Integer.valueOf(c_siteopf_id.toString().trim()); + } + + public static boolean isEquals(String c_snet_id,String s) { + if(c_snet_id==null){ + return false; + } + if (c_snet_id.equals(s)){ + return true; + }else { + return false; + } + } + public static double add(double v1, double v2) { + BigDecimal b1=new BigDecimal(Double.toString(v1)); + BigDecimal b2 = new BigDecimal(Double.toString(v2)); + return b1.add(b2).doubleValue(); + } +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/CompareTime.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/CompareTime.java new file mode 100644 index 000000000..bfe3a972e --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/CompareTime.java @@ -0,0 +1,56 @@ +package com.example.awaysuse.util; + +import com.example.awaysuse.model.Person; +import org.apache.commons.lang3.builder.ToStringExclude; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.stream.Collectors; + +public class CompareTime { + private static SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss"); + + /** + * 判断当前时间是否在某个时间段内 + * begin 开始时间字符串 String begin="09:00:00"; + * end 结束时间字符串 String end="12:00:00"; + */ + public static boolean compareTime(String begin, String end) { + boolean result = false; + //将时间字符串转化成时间 + + try { + //转换成时间格式 + Date beginTime = df.parse(begin); + Date endTime = df.parse(end); + //取出当前时间的时分秒编码再解码 + Date date = df.parse(df.format(new Date())); + //通过日历形式开始比较 + Calendar b = Calendar.getInstance(); + b.setTime(beginTime); + Calendar e = Calendar.getInstance(); + e.setTime(endTime); + Calendar d = Calendar.getInstance(); + d.setTime(date); + //当前时间晚于开始时间,早于结束时间则表明在指定的时间段内 + if (d.after(b) && d.before(e)) { + result = true; + } + } catch (ParseException e1) { + e1.printStackTrace(); + + } + return result; + } + + public static void main(String[] args) { + /* boolean b = compareTime("09:00:00", "18:00:00"); + System.out.println(b);*/ + + + } + + + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/DataCalcUtils.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/DataCalcUtils.java new file mode 100644 index 000000000..e7f92ac63 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/DataCalcUtils.java @@ -0,0 +1,115 @@ +package com.example.awaysuse.util; + +import java.math.BigDecimal; + +/** + * @Description 一些常用的数学计算 + */ +public class DataCalcUtils { + + /** + * 默认精确到2位小数 + */ + private static final int DEF_DIV_SCALE = 2; + + private DataCalcUtils() { + } + + /** + * 提供精确的加法运算。 + * + * @param v1 + * 被加数 + * @param v2 + * 加数 + * @return 两个参数的和 + */ + public static double add(double v1, double v2) { + BigDecimal b1 = new BigDecimal(Double.toString(v1)); + BigDecimal b2 = new BigDecimal(Double.toString(v2)); + return b1.add(b2).doubleValue(); + } + + /** + * 提供精确的减法运算。 + * + * @param v1 + * 被减数 + * @param v2 + * 减数 + * @return 两个参数的差 + */ + public static double sub(double v1, double v2) { + BigDecimal b1 = new BigDecimal(Double.toString(v1)); + BigDecimal b2 = new BigDecimal(Double.toString(v2)); + return b1.subtract(b2).doubleValue(); + } + + /** + * 提供精确的乘法运算。 + * + * @param v1 + * 被乘数 + * @param v2 + * 乘数 + * @return 两个参数的积 + */ + public static double mul(double v1, double v2) { + BigDecimal b1 = new BigDecimal(Double.toString(v1)); + BigDecimal b2 = new BigDecimal(Double.toString(v2)); + return b1.multiply(b2).doubleValue(); + } + + /** + * 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到 小数点以后10位,以后的数字四舍五入。 + * + * @param v1 + * 被除数 + * @param v2 + * 除数 + * @return 两个参数的商 + */ + public static double div(double v1, double v2) { + return div(v1, v2, DEF_DIV_SCALE); + } + + /** + * 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指 定精度,以后的数字四舍五入。 + * + * @param v1 + * 被除数 + * @param v2 + * 除数 + * @param scale + * 表示表示需要精确到小数点以后几位。 + * @return 两个参数的商 + */ + public static double div(double v1, double v2, int scale) { + if (scale < 0) { + throw new IllegalArgumentException( + "The scale must be a positive integer or zero"); + } + BigDecimal b1 = new BigDecimal(Double.toString(v1)); + BigDecimal b2 = new BigDecimal(Double.toString(v2)); + return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); + } + + /** + * 提供精确的小数位四舍五入处理。 + * + * @param v + * 需要四舍五入的数字 + * @param scale + * 小数点后保留几位 + * @return 四舍五入后的结果 + */ + public static double round(double v, int scale) { + if (scale < 0) { + throw new IllegalArgumentException( + "The scale must be a positive integer or zero"); + } + BigDecimal b = new BigDecimal(Double.toString(v)); + BigDecimal one = new BigDecimal("1"); + return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); + } +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/DemoResourceSync.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/DemoResourceSync.java new file mode 100644 index 000000000..de8e21589 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/DemoResourceSync.java @@ -0,0 +1,164 @@ +package com.example.awaysuse.util; + + +import com.alibaba.fastjson.JSONObject; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; + +public class DemoResourceSync { + + public static void main(String[] args) { + DemoResourceSync dr = new DemoResourceSync(); + dr.run(); + } + + public void run() { + ResThread resThread = new ResThread(); + for (int i = 0; i < 10; i++) { //10个线程去跑 + new Thread(resThread, "线程" + i).start(); + } + + PerfThread perfThread = new PerfThread(); + for (int i = 0; i < 20; i++) { //20个线程去跑 + new Thread(perfThread, "线程" + i).start(); + } + + StateThread stateThread = new StateThread(); + for (int i = 0; i < 20; i++) { //20个线程去跑 + new Thread(stateThread, "线程" + i).start(); + } + } + + /** + * 同步资源 + * @author Administrator + * + */ + private class ResThread implements Runnable { + + public ResThread() { + } + + @Override + public void run() { + synchronized (this) { + SimpleDateFormat sdf = new SimpleDateFormat( + "yyyy-MM-dd HH:mm:ss"); + String datestr = sdf.format(new Date()); + String str = "["; + for (int i = 0; i < 900; i++) { + str += "{\"classCode\":\"Switch\",\"domainId\":\"rootDomain\",\"sourceId\":\"192.168." + + Thread.currentThread().getId() + + "." + + i + + "\",\"updateTime\":\"" + + datestr + + "\",\"values\":{\"name\":\"交换机" + + Thread.currentThread().getId() + + i + + "\",\"ipAddr\":\"192.168." + + Thread.currentThread().getId() + + "." + + i + + "\"}},"; + } + str = str.substring(0, str.length() - 1) + "]"; + System.out.println("resThread:"+str); + String url = "http://127.0.0.1:8890/api/v2/cmdb/cis/save-batch"; + try { + JSONObject jsonObject = HttpClientUtils.httpPost(url, str); + String result = jsonObject.getString("result"); + System.out.println("resThreadResult" + + Thread.currentThread().getId() + ":" + result); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + + /** + * 同步性能 + * @author Administrator + * + */ + private class PerfThread implements Runnable { + + public PerfThread() { + } + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Calendar calendar = Calendar.getInstance(); + + @Override + public void run() { + synchronized (this) { + String str = "["; + for (int i = 500; i > 0; i--) { + String datestr = sdf.format(new Date((calendar + .getTimeInMillis() - (1000 * Thread.currentThread() + .getId() * (i + 1))))); + str += "{\"ciId\":\"3a98052b-794c-4531-9182-611625c102a4\",\"groupCode\":\"ram-use\"," + + "\"sampleTime\":\"" + + datestr + + "\",\"indicators\":{\"mem_used\":500,\"mem_usage\":97}},"; + } + str = str.substring(0, str.length() - 1) + "]"; + System.out.println("perfThread:"+str); + String url = "http://127.0.0.1:8890/api/v2/pmdb/perf-groups/create"; + try { + JSONObject jsonObject = HttpClientUtils.httpPost(url, str); + String result = jsonObject.getString("result"); + System.out.println("perfThreadResult" + + Thread.currentThread().getId() + ":" + result); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + + /** + * 同步状态 + * @author Administrator + * + */ + private class StateThread implements Runnable { + + public StateThread() { + } + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Calendar calendar = Calendar.getInstance(); + + @Override + public void run() { + synchronized (this) { + String str = "["; + for (int i = 500; i > 0; i--) { + String datestr = sdf.format(new Date((calendar + .getTimeInMillis() - (1000 * Thread.currentThread() + .getId() * (i + 1))))); + str += "{\"ciId\":\"3a98052b-794c-4531-9182-611625c102a4\",\"typeCode\":\"available_status\"," + + "\"sampleTime\":\"" + + datestr + + "\",\"value\":\"1\",\"descr\":\"可用\"},"; + } + str = str.substring(0, str.length() - 1) + "]"; + System.out.println("stateThread:"+str); + String url = "http://127.0.0.1:8890/api/v2/pmdb/states/create"; + try { + JSONObject jsonObject = HttpClientUtils.httpPost(url, str); + String result = jsonObject.getString("result"); + System.out.println("stateThreadResult" + + Thread.currentThread().getId() + ":" + result); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } +} + diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/ESUtils.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/ESUtils.java new file mode 100644 index 000000000..7155f45d8 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/ESUtils.java @@ -0,0 +1,662 @@ +package com.example.awaysuse.util; + + +import com.example.awaysuse.model.Doc; +import com.example.awaysuse.model.PageData; +import lombok.extern.slf4j.Slf4j; +import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; +import org.elasticsearch.action.bulk.BulkRequest; +import org.elasticsearch.action.bulk.BulkResponse; +import org.elasticsearch.action.delete.DeleteRequest; +import org.elasticsearch.action.delete.DeleteResponse; +import org.elasticsearch.action.get.GetRequest; +import org.elasticsearch.action.get.GetResponse; +import org.elasticsearch.action.index.IndexRequest; +import org.elasticsearch.action.index.IndexResponse; +import org.elasticsearch.action.search.ClearScrollRequest; +import org.elasticsearch.action.search.SearchRequest; +import org.elasticsearch.action.search.SearchResponse; +import org.elasticsearch.action.search.SearchScrollRequest; +import org.elasticsearch.action.support.master.AcknowledgedResponse; +import org.elasticsearch.action.update.UpdateRequest; +import org.elasticsearch.action.update.UpdateResponse; +import org.elasticsearch.client.RequestOptions; +import org.elasticsearch.client.RestHighLevelClient; +import org.elasticsearch.client.core.CountRequest; +import org.elasticsearch.client.core.CountResponse; +import org.elasticsearch.client.indices.CreateIndexRequest; +import org.elasticsearch.client.indices.CreateIndexResponse; +import org.elasticsearch.client.indices.GetIndexRequest; +import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.common.unit.TimeValue; +import org.elasticsearch.common.xcontent.XContentType; +import org.elasticsearch.index.query.BoolQueryBuilder; +import org.elasticsearch.index.query.QueryBuilder; +import org.elasticsearch.rest.RestStatus; +import org.elasticsearch.search.Scroll; +import org.elasticsearch.search.SearchHit; +import org.elasticsearch.search.SearchHits; +import org.elasticsearch.search.aggregations.AggregationBuilder; +import org.elasticsearch.search.aggregations.AggregationBuilders; +import org.elasticsearch.search.aggregations.bucket.terms.Terms; +import org.elasticsearch.search.aggregations.metrics.Sum; +import org.elasticsearch.search.aggregations.metrics.TopHits; +import org.elasticsearch.search.builder.SearchSourceBuilder; +import org.elasticsearch.search.sort.SortOrder; +import org.springframework.stereotype.Component; +import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; + +import javax.annotation.Resource; +import java.util.*; + +/** + * @author fengh + * @Date: 2020/8/18 10:17 + * @Description: elasticsearch工具类 + */ +@Slf4j +@Component +public class ESUtils { + + @Resource(name = "restHighLevelClient") + private RestHighLevelClient client; + + /** + * 检查索引是否存在 + * + * @param index 索引名称 + * @return boolean + */ + public boolean existIndex(String index) { + try { + GetIndexRequest request = new GetIndexRequest(index); + return client.indices().exists(request, RequestOptions.DEFAULT); + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + /** + * 创建索引 + * + * @param index 索引名称 + * @return boolean + */ + public boolean createIndex(String index) { + return createIndex(index, null); + } + + /** + * 创建索引 + * + * @param index 索引名称 + * @param source 配置 + * @return boolean + */ + public boolean createIndex(String index, String source) { + try { + CreateIndexRequest createIndexRequest = new CreateIndexRequest(index); + //指定字段个数最大10000 + createIndexRequest.settings(Settings.builder().put("index.mapping.total_fields.limit", 10000)); + if (!StringUtils.isEmpty(source)) { + createIndexRequest.mapping(source, XContentType.JSON); + } + CreateIndexResponse response = client.indices().create(createIndexRequest, RequestOptions.DEFAULT); + return response.isAcknowledged(); + } catch (Exception e) { + log.error("创建索引{}异常", index, e); + } + return false; + } + + /** + * 删除索引 + * + * @param index 索引名称 + * @return boolean + */ + public boolean deleteIndex(String index) { + try { + DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index); + AcknowledgedResponse acknowledgedResponse = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT); + return acknowledgedResponse.isAcknowledged(); + } catch (Exception e) { + log.error("删除索引{}异常", index, e); + } + return false; + } + + /** + * 新增(更新)文档:自动生成文档id + * + * @param index 索引 + * @param map 保存的数据 + * @return string + */ + public String save(String index, Map map) { + return save(index, map, null); + } + + /** + * 新增(更新)文档:自定义文档id + * + * @param index 索引 + * @param docId 文档id + * @param map 保存的数据 + * @return string + */ + public String save(String index, Map map, String docId) { + try { + //文档id为空则新增 + if(StringUtils.isEmpty(docId)){ + IndexRequest indexRequest = new IndexRequest().index(index).source(map); + IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT); + return indexResponse.getId(); + } + UpdateRequest updateRequest = new UpdateRequest().index(index).id(docId).doc(map).docAsUpsert(true); + UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT); + return updateResponse.getId(); + } catch (Exception e) { + log.error("索引{}插入(更新)数据异常:{}", index, e); + } + return null; + } + + /** + * 批量插入(更新)文档: 自动生成id + * + * @param index 索引 + * @param list 保存的数据 + * @return boolean + */ + public boolean bulkSave(String index, List> list) { + return bulkSave(index, list, null); + } + + /** + * 批量插入(更新)文档: 自定义id + * + * @param index 索引 + * @param list 保存的数据 + * @param idField map中作为文档id的字段名称 + * @return boolean + */ + public boolean bulkSave(String index, List> list, String idField) { + return bulkSave(index, list, idField, null); + } + + /** + * 批量插入(更新)文档: 自定义id字段 自定义id前缀 + * + * @param index 索引 + * @param list 保存的数据 + * @param idField map中作为文档id的字段名称 + * @param prefix id前缀 + * @return boolean + */ + public boolean bulkSave(String index, List> list, String idField, String prefix) { + if (CollectionUtils.isEmpty(list)) { + return false; + } + try { + BulkRequest bulkRequest = new BulkRequest(); + for (Map map : list) { + String docId = null; + if (!StringUtils.isEmpty(idField) && StringUtils.isEmpty(prefix)) { + docId = String.valueOf(map.get(idField)); + } else if (!StringUtils.isEmpty(idField) && !StringUtils.isEmpty(prefix)) { + docId = prefix + map.get(idField); + } + //文档id为空则新增 + if(StringUtils.isEmpty(docId)){ + IndexRequest indexRequest = new IndexRequest().index(index).source(map); + bulkRequest.add(indexRequest); + } else { + UpdateRequest updateRequest = new UpdateRequest().index(index).id(docId).doc(map).docAsUpsert(true); + bulkRequest.add(updateRequest); + } + } + BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT); + if(bulkResponse.hasFailures()){ + log.error("索引{}批量插入(更新)数据错误:{}", index, bulkResponse.buildFailureMessage()); + return false; + } + return true; + } catch (Exception e) { + log.error("索引{}批量插入(更新)数据异常", index, e); + } + return false; + } + + /** + * 根据文档id查询文档 + * + * @param index 索引 + * @param docId 文档id + * @return map + */ + public Doc searchById(String index, String docId) { + try { + GetRequest getRequest = new GetRequest(index).id(docId); + GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT); + if (getResponse.isExists()) { + return Doc.put(getResponse.getSourceAsMap()).build(); + } + } catch (Exception e) { + log.error("索引{}查询文档id={}异常", index, docId, e); + } + return null; + } + + /** + * 根据文档id删除文档 + * + * @param index 索引 + * @param docId 文档id + * @return boolean + */ + public boolean deleteById(String index, String docId) { + try { + DeleteRequest deleteRequest = new DeleteRequest(index).id(docId); + DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT); + return deleteResponse.status() == RestStatus.OK; + } catch (Exception e) { + log.error("删除索引{}中文档id={}异常", index, docId); + e.printStackTrace(); + } + return false; + } + + /** + * 分页查询 + * + * @param index 索引 + * @param pageNum 当前页码 + * @param pageSize 每页条数 + * @return pageData + */ + public PageData> searchPage(String index, Integer pageNum, Integer pageSize) { + return searchPage(index, null, pageNum, pageSize, null, null); + } + + /** + * 分页查询: 按指定排序 + * + * @param index 索引 + * @param pageNum 当前页码 + * @param pageSize 每页条数 + * @return pageData + */ + public PageData> searchPage(String index, Integer pageNum, Integer pageSize, String sortField, Boolean desc) { + return searchPage(index, null, pageNum, pageSize, sortField, desc); + } + + /** + * 分页查询: 带查询条件 + * + * @param index 索引 + * @param query 查询条件 + * @param pageNum 当前页码 + * @param pageSize 每页条数 + * @return pageData + */ + public PageData> searchPage(String index, QueryBuilder query, Integer pageNum, Integer pageSize) { + return searchPage(index, query, pageNum, pageSize, null, null); + } + + /** + * 分页查询: 带查询条件 指定字段排序 + * + * @param index 索引 + * @param query 查询条件 + * @param pageNum 当前页码 + * @param pageSize 每页条数 + * @param sortField 排序字段 + * @param desc 是否倒序 + * @return pageData + */ + public PageData> searchPage(String index, QueryBuilder query, Integer pageNum, Integer pageSize, String sortField, Boolean desc) { + return searchPageExecute(index, query, pageNum, pageSize, sortField, desc); + } + + /** + * 执行分页查询 + * + * @param index 索引 + * @param query 查询条件 + * @param pageNum 当前页码 + * @param pageSize 每页条数 + * @param sortField 排序字段 + * @param desc 是否倒序 + * @return pageData + */ + private PageData> searchPageExecute(String index, QueryBuilder query, Integer pageNum, Integer pageSize, String sortField, Boolean desc) { + List searchResult = new ArrayList<>(); + SearchSourceBuilder sourceBuilder = new SearchSourceBuilder().query(query); + try { + if (pageNum == null || pageNum <= 0) { + pageNum = 1; + } + if (pageSize == null || pageSize <= 0) { + pageSize = 10; + } + int from = (pageNum - 1) * pageSize;//计算起始下标 + sourceBuilder.from(from);//起始下标,从0开始 + sourceBuilder.size(pageSize);//每页记录数 + + setSortQuery(sourceBuilder, sortField, desc);//设置排序信息 + + SearchRequest searchRequest = new SearchRequest(index).source(sourceBuilder); + SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); + SearchHits hits = searchResponse.getHits(); + long totalCount = hits.getTotalHits().value; + if (totalCount == 0) { + return new PageData<>(); + } + int totalPage = Math.toIntExact(hits.getTotalHits().value / pageSize); + if(totalCount % 10 != 0){ + totalPage ++; + } + SearchHit[] searchHits = hits.getHits(); + Arrays.stream(searchHits).forEach(doc -> searchResult.add(Doc.put(doc.getSourceAsMap()).build())); + return new PageData<>(pageNum, pageSize, totalCount, totalPage, searchResult); + } catch (Exception e) { + log.error("索引{}查询分页数据失败, 查询条件{}", index, sourceBuilder.toString(), e); + } + return new PageData<>(); + } + + /** + * 查询 + * + * @param index 索引 + * @return list + */ + public List search(String index) { + return search(index, null); + } + + /** + * 查询 + * + * @param index 索引 + * @param query 查询条件 + * @return list + */ + public List search(String index, QueryBuilder query) { + return search(index, query, null, null); + } + + /** + * 查询 + * + * @param index 索引名称 + * @param sortField 排序字段 + * @param desc 是否倒序 + * @return list + */ + public List search(String index, String sortField, Boolean desc) { + return search(index, null, sortField, desc); + } + + /** + * 查询 + * + * @param index 索引名称 + * @param query 查询条件 + * @param sortField 排序字段 + * @param desc 是否倒序 + * @return list + */ + public List search(String index, QueryBuilder query, String sortField, Boolean desc) { + return search(index, query, sortField, desc, null); + } + + /** + * 查询 + * + * @param index 索引名称 + * @param sortField 排序字段 + * @param desc 是否倒序 + * @param size 查询条数 null 或 小于0表示查询所有 + * @return list + */ + public List search(String index, String sortField, Boolean desc, Integer size) { + return search(index, null, sortField, desc, size); + } + + /** + * 查询 + * + * @param index 索引名称 + * @param query 查询条件 + * @param sortField 排序字段 + * @param desc 是否倒序 + * @param size 查询条数 null 或 小于0表示查询所有 + * @return list + */ + public List search(String index, QueryBuilder query, String sortField, Boolean desc, Integer size) { + return searchExecute(index, query, sortField, desc, size); + } + + /** + * 执行查询: 游标查询,每次查询一万条,查询所有数据 + * + * @param index 索引 + * @param query 查询条件 + * @param sortField 排序字段 + * @param desc 是否倒序 + * @param size 查询条数 null 或 小于0表示查询所有 + * @return list + */ + private List searchExecute(String index, QueryBuilder query, String sortField, Boolean desc, Integer size) { + List searchResult = new ArrayList<>(); + SearchSourceBuilder sourceBuilder = new SearchSourceBuilder().query(query); + try { + setSortQuery(sourceBuilder, sortField, desc);//设置排序信息 + /* + * 当size不为空且大于0时,限制查询条数为size + */ + if(size != null && size > 0){ + sourceBuilder.size(size); + SearchRequest searchRequest = new SearchRequest(index).source(sourceBuilder); + SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); + SearchHits hits = searchResponse.getHits(); + int totalCount = hits.getHits().length; + if (totalCount == 0) { + return searchResult; + } + SearchHit[] searchHits = hits.getHits(); + Arrays.stream(searchHits).forEach(doc -> searchResult.add(Doc.put(doc.getSourceAsMap()).build())); + return searchResult; + } + + /* + * 否则查询所有,设置游标size为10000,每次查询10000条,查询全部数据 + */ + sourceBuilder.size(10000); + Scroll scroll = new Scroll(TimeValue.timeValueSeconds(30)); + SearchRequest searchRequest = new SearchRequest(index).source(sourceBuilder).scroll(scroll); + SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); + SearchHits hits = searchResponse.getHits(); + if (hits.getHits().length == 0) { + return searchResult; + } + SearchHit[] searchHits = hits.getHits(); + Arrays.stream(searchHits).forEach(doc -> searchResult.add(Doc.put(doc.getSourceAsMap()).build())); + String scrollId = searchResponse.getScrollId(); + while (true) { + SearchScrollRequest searchScrollRequest = new SearchScrollRequest(scrollId).scroll(scroll); + searchResponse = client.scroll(searchScrollRequest, RequestOptions.DEFAULT); + searchHits = searchResponse.getHits().getHits(); + if (searchHits == null || searchHits.length == 0) { + break; + } + Arrays.stream(searchHits).forEach(doc -> searchResult.add(Doc.put(doc.getSourceAsMap()).build())); + scrollId = searchResponse.getScrollId(); + } + //清除滚屏 + ClearScrollRequest clearScrollRequest = new ClearScrollRequest(); + clearScrollRequest.addScrollId(scrollId); + client.clearScroll(clearScrollRequest, RequestOptions.DEFAULT); + return searchResult; + } catch (Exception e) { + log.error("索引{}查询数据失败, 查询条件{}", index, sourceBuilder.toString(), e); + } + return searchResult; + } + + /** + * 单个字段聚合统计count + * + * @param index 索引 + * @param field 聚合字段 + * @param size 条数: 空默认10条 + * @return map + */ + public Map searchAggCount(String index, String field, Integer size) { + return searchAggCount(index, null, field, size); + } + + /** + * 单个字段聚合统计count: 带查询条件 + * + * @param index 索引 + * @param field 聚合字段 + * @param size 条数: 空默认10条 + * @return map + */ + public Map searchAggCount(String index, BoolQueryBuilder query, String field, Integer size) { + try { + AggregationBuilder aggregationBuilder = AggregationBuilders.terms("aggCount").field(field).size(size == null || size < 0 ? 10 : size); + SearchSourceBuilder sourceBuilder = new SearchSourceBuilder().query(query).aggregation(aggregationBuilder); + SearchRequest searchRequest = new SearchRequest(index).source(sourceBuilder); + SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); + Terms terms = searchResponse.getAggregations().get("aggCount"); + Map map = new LinkedHashMap<>(); + for (Terms.Bucket entry : terms.getBuckets()) { + String key = (String) entry.getKey(); + long total = entry.getDocCount(); + map.put(key, total); + } + return map; + } catch (Exception e) { + log.error("统计字段{} count异常", field, e); + } + return null; + } + + /** + * 单个字段聚合统计sum + * + * @param index 索引 + * @param field 聚合字段 + * @return map + */ + public Map searchAggSum(String index, String field) { + try { + AggregationBuilder aggregationBuilder = AggregationBuilders.sum("aggSum").field(field); + SearchSourceBuilder sourceBuilder = new SearchSourceBuilder().aggregation(aggregationBuilder); + SearchRequest searchRequest = new SearchRequest(index).source(sourceBuilder); + SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); + Sum sum = searchResponse.getAggregations().get("aggSum"); + Map map = new HashMap<>(); + map.put(field, sum.getValue()); + return map; + } catch (Exception e) { + log.error("统计字段{} sum异常", field, e); + } + return null; + } + + /** + * 单个字段聚合(去重)查询数据 + * + * @param index 索引 + * @param query 查询条件 + * @param field 统计字段 + * @param pageNum 页数 + * @param pageSize 每页条数 + * @return pageData + */ + public PageData> searchAggDocs(String index, QueryBuilder query, String field, Integer pageNum, Integer pageSize, String sortField, Boolean desc) { + try { + AggregationBuilder aggregationBuilder = AggregationBuilders + .terms("agg").field(field).size(100000) + .subAggregation(AggregationBuilders.topHits("dataHits") + .size(1));//聚合后只需要重复中的一条 + + SearchSourceBuilder sourceBuilder = new SearchSourceBuilder().query(query).aggregation(aggregationBuilder); + setSortQuery(sourceBuilder, sortField, desc);//设置排序信息 + SearchRequest searchRequest = new SearchRequest(index).source(sourceBuilder); + SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); + Terms terms = searchResponse.getAggregations().get("agg"); + List searchList = new ArrayList<>(); + for (Terms.Bucket entry : terms.getBuckets()) { + TopHits top = entry.getAggregations().get("dataHits"); + for (SearchHit hit : top.getHits()) { + searchList.add(Doc.put(hit.getSourceAsMap()).build()); + } + } + if (pageNum == null || pageNum <= 0) { + pageNum = 1; + } + if (pageSize == null || pageSize <= 0) { + pageSize = 10; + } + int from = (pageNum - 1) * pageSize;//起始下标 + int totalCount = searchList.size();//全部条数 + int totalPage = searchList.size() / pageSize + 1;//全部页数 + + if (from >= searchList.size()) { + return new PageData<>(); + } + if (from + pageSize >= searchList.size()) { + return new PageData<>(pageNum, pageSize, totalCount, totalPage, searchList.subList(from, searchList.size())); + } + return new PageData<>(pageNum, pageSize, totalCount, totalPage, searchList.subList(from, from + pageSize)); + } catch (Exception e) { + e.printStackTrace(); + } + return new PageData<>(); + } + + /** + * 查询count + * + * @param index 索引 + * @param query 查询条件 + * @return long + */ + public long count(String index, QueryBuilder query) { + try { + CountRequest countRequest = new CountRequest().indices(index).query(query); + CountResponse countResponse= client.count(countRequest, RequestOptions.DEFAULT); + return countResponse.getCount(); + } catch (Exception e) { + e.printStackTrace(); + } + return 0; + } + + /** + * 设置排序信息 + * + * @param sourceBuilder + * @param sortField + * @param desc + */ + private void setSortQuery(SearchSourceBuilder sourceBuilder, String sortField, Boolean desc) { + if (!StringUtils.isEmpty(sortField) && desc != null) { + if (desc) { + sourceBuilder.sort(sortField, SortOrder.DESC); + } else { + sourceBuilder.sort(sortField, SortOrder.ASC); + } + } + } + + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/ExcelUtils.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/ExcelUtils.java new file mode 100644 index 000000000..5a41dae07 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/ExcelUtils.java @@ -0,0 +1,402 @@ +package com.example.awaysuse.util; + +import org.apache.commons.lang3.StringUtils; +import org.apache.poi.hssf.usermodel.*; +import org.apache.poi.hssf.util.HSSFColor; +import org.apache.poi.ss.util.CellRangeAddress; +import org.apache.poi.xssf.usermodel.*; + +import java.io.OutputStream; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.text.SimpleDateFormat; +import java.util.Collection; +import java.util.Date; +import java.util.Iterator; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + + + +/** + * 导出Excel + * @author liuyazhuang + * + * @param + */ +public class ExcelUtils{ + + // 2007 版本以上 最大支持1048576行 + public final static String EXCEl_FILE_2007 = "2007"; + // 2003 版本 最大支持65536 行 + public final static String EXCEL_FILE_2003 = "2003"; + + /** + *

+ * 导出无头部标题行Excel
+ * 时间格式默认:yyyy-MM-dd hh:mm:ss
+ *

+ * + * @param title 表格标题 + * @param dataset 数据集合 + * @param version 2003 或者 2007,不传时默认生成2003版本 + */ + public void exportExcel(String title, String sheetName, Collection dataset, String version) { + if(StringUtils.isEmpty(version) || EXCEL_FILE_2003.equals(version.trim())){ + exportExcel2003(title, sheetName, null, dataset, "yyyy-MM-dd HH:mm:ss"); + }else{ + exportExcel2007(title, sheetName, null, dataset, "yyyy-MM-dd HH:mm:ss"); + } + } + + /** + *

+ * 导出带有头部标题行的Excel
+ * 时间格式默认:yyyy-MM-dd hh:mm:ss
+ *

+ * + * @param title 表格标题 + * @param headers 头部标题集合 + * @param dataset 数据集合 + * @param out 输出流 + * @param version 2003 或者 2007,不传时默认生成2003版本 + */ + public void exportExcel(String title, String sheetName,String[] headers, Collection dataset, OutputStream out,String version) { + if(StringUtils.isBlank(version) || EXCEL_FILE_2003.equals(version.trim())){ + exportExcel2003(title, sheetName, headers, dataset, "yyyy-MM-dd HH:mm:ss"); + }else{ + exportExcel2007(title, sheetName, headers, dataset, "yyyy-MM-dd HH:mm:ss"); + } + } + + /** + *

+ * 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中
+ * 此版本生成2007以上版本的文件 (文件后缀:xlsx) + *

+ * + * @param title + * 表格标题名 + * @param headers + * 表格头部标题集合 + * @param dataset + * 需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的 + * JavaBean属性的数据类型有基本数据类型及String,Date + * @param pattern + * 如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss" + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + public XSSFWorkbook exportExcel2007(String title, String sheetName, String[] headers, Collection dataset, String pattern) { + // 声明一个工作薄 + XSSFWorkbook workbook = new XSSFWorkbook(); + // 生成一个表格 + XSSFSheet sheet = workbook.createSheet(sheetName); + // 设置表格默认列宽度为15个字节 + sheet.setDefaultColumnWidth(20); + // 生成一个样式 + XSSFCellStyle style = workbook.createCellStyle(); + // 设置这些样式 + style.setFillForegroundColor(new XSSFColor(java.awt.Color.gray)); + style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND); + style.setBorderBottom(XSSFCellStyle.BORDER_THIN); + style.setBorderLeft(XSSFCellStyle.BORDER_THIN); + style.setBorderRight(XSSFCellStyle.BORDER_THIN); + style.setBorderTop(XSSFCellStyle.BORDER_THIN); + style.setAlignment(XSSFCellStyle.ALIGN_CENTER); + // 生成一个字体 + XSSFFont font = workbook.createFont(); + font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD); + font.setFontName("宋体"); + font.setColor(new XSSFColor(java.awt.Color.BLACK)); + font.setFontHeightInPoints((short) 11); + // 把字体应用到当前的样式 + style.setFont(font); + // 生成并设置另一个样式 + XSSFCellStyle style2 = workbook.createCellStyle(); + style2.setFillForegroundColor(new XSSFColor(java.awt.Color.WHITE)); + style2.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND); + style2.setBorderBottom(XSSFCellStyle.BORDER_THIN); + style2.setBorderLeft(XSSFCellStyle.BORDER_THIN); + style2.setBorderRight(XSSFCellStyle.BORDER_THIN); + style2.setBorderTop(XSSFCellStyle.BORDER_THIN); + style2.setAlignment(XSSFCellStyle.ALIGN_CENTER); + style2.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); + // 生成另一个字体 + XSSFFont font2 = workbook.createFont(); + font2.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL); + // 把字体应用到当前的样式 + style2.setFont(font2); + + // 产生表格标题行 + XSSFRow row = sheet.createRow(0); + XSSFCell cellHeader; + for (int i = 0; i < headers.length; i++) { + cellHeader = row.createCell(i); + cellHeader.setCellStyle(style); + cellHeader.setCellValue(new XSSFRichTextString(headers[i])); + } + + // 遍历集合数据,产生数据行 + Iterator it = dataset.iterator(); + int index = 0; + T t; + Field[] fields; + Field field; + XSSFRichTextString richString; + Pattern p = Pattern.compile("^//d+(//.//d+)?$"); + Matcher matcher; + String fieldName; + String getMethodName; + XSSFCell cell; + Class tCls; + Method getMethod; + Object value; + String textValue; + SimpleDateFormat sdf = new SimpleDateFormat(pattern); + while (it.hasNext()) { + index++; + row = sheet.createRow(index); + t = (T) it.next(); + // 利用反射,根据JavaBean属性的先后顺序,动态调用getXxx()方法得到属性值 + fields = t.getClass().getDeclaredFields(); + for (int i = 0; i < fields.length; i++) { + cell = row.createCell(i); + cell.setCellStyle(style2); + field = fields[i]; + fieldName = field.getName(); + getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + + fieldName.substring(1); + try { + tCls = t.getClass(); + getMethod = tCls.getMethod(getMethodName, new Class[] {}); + value = getMethod.invoke(t, new Object[] {}); + // 判断值的类型后进行强制类型转换 + textValue = null; + if (value instanceof Integer) { + cell.setCellValue((Integer) value); + } else if (value instanceof Float) { + textValue = String.valueOf((Float) value); + cell.setCellValue(textValue); + } else if (value instanceof Double) { + textValue = String.valueOf((Double) value); + cell.setCellValue(textValue); + } else if (value instanceof Long) { + cell.setCellValue((Long) value); + } + if (value instanceof Boolean) { + textValue = "是"; + if (!(Boolean) value) { + textValue = "否"; + } + } else if (value instanceof Date) { + textValue = sdf.format((Date) value); + } else { + // 其它数据类型都当作字符串简单处理 + if (value != null) { + textValue = value.toString(); + } + } + if (textValue != null) { + matcher = p.matcher(textValue); + if (matcher.matches()) { + // 是数字当作double处理 + cell.setCellValue(Double.parseDouble(textValue)); + } else { + richString = new XSSFRichTextString(textValue); + cell.setCellValue(richString); + } + } + } catch (SecurityException e) { + e.printStackTrace(); + } catch (NoSuchMethodException e) { + e.printStackTrace(); + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (InvocationTargetException e) { + e.printStackTrace(); + } finally { + // 清理资源 + } + } + } + return workbook; + } + + + + /** + *

+ * 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中
+ * 此方法生成2003版本的excel,文件名后缀:xls
+ *

+ * + * @param sheetName + * 表格sheet名 + * @param headers + * 表格头部标题集合 + * @param dataset + * 需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的 + * JavaBean属性的数据类型有基本数据类型及String,Date + * @param pattern + * 如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss" + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + public HSSFWorkbook exportExcel2003(String title, String sheetName, String[] headers, Collection dataset, String pattern) { + // 声明一个工作薄 + HSSFWorkbook workbook = new HSSFWorkbook(); + // 生成一个表格 + HSSFSheet sheet = workbook.createSheet(sheetName); + // 设置表格默认列宽度为15个字节 + sheet.setDefaultColumnWidth(20); + // 生成一个样式 + HSSFCellStyle style = workbook.createCellStyle(); + // 设置这些样式 + style.setFillForegroundColor(HSSFColor.GREY_50_PERCENT.index); + style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); + style.setBorderBottom(HSSFCellStyle.BORDER_THIN); + style.setBorderLeft(HSSFCellStyle.BORDER_THIN); + style.setBorderRight(HSSFCellStyle.BORDER_THIN); + style.setBorderTop(HSSFCellStyle.BORDER_THIN); + style.setAlignment(HSSFCellStyle.ALIGN_CENTER); + // 生成一个字体 + HSSFFont font = workbook.createFont(); + font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); + font.setFontName("宋体"); + font.setColor(HSSFColor.WHITE.index); + font.setFontHeightInPoints((short) 11); + // 把字体应用到当前的样式 + style.setFont(font); + // 生成并设置另一个样式 + HSSFCellStyle style2 = workbook.createCellStyle(); + style2.setFillForegroundColor(HSSFColor.WHITE.index); + style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); + style2.setBorderBottom(HSSFCellStyle.BORDER_THIN); + style2.setBorderLeft(HSSFCellStyle.BORDER_THIN); + style2.setBorderRight(HSSFCellStyle.BORDER_THIN); + style2.setBorderTop(HSSFCellStyle.BORDER_THIN); + style2.setAlignment(HSSFCellStyle.ALIGN_CENTER); + style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); + // 生成另一个字体 + HSSFFont font2 = workbook.createFont(); + font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL); + // 把字体应用到当前的样式 + style2.setFont(font2); + + //=======================创建标题 + CellRangeAddress region = new CellRangeAddress(0, 0, 0, headers.length-1); + sheet.addMergedRegion(region); + // 生成一个样式 + HSSFCellStyle headerStyle = workbook.createCellStyle(); + headerStyle.setFillForegroundColor(HSSFColor.WHITE.index); + headerStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); + headerStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); + headerStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN); + headerStyle.setBorderRight(HSSFCellStyle.BORDER_THIN); + headerStyle.setBorderTop(HSSFCellStyle.BORDER_THIN); + headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); + headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); + // 生成一个字体 + HSSFFont headerFont = workbook.createFont(); + headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); + headerFont.setFontName("宋体"); + headerFont.setColor(HSSFColor.BLACK.index); + headerFont.setFontHeightInPoints((short) 15); + // 把字体应用到当前的样式 + headerStyle.setFont(headerFont); + HSSFRow headerRow = sheet.createRow(0); + HSSFCell headerCell = headerRow.createCell(0);; + headerCell.setCellStyle(headerStyle); + headerCell.setCellValue(title); + + // 产生表格标题行 + HSSFRow row = sheet.createRow(1); + HSSFCell cellHeader; + for (int i = 0; i < headers.length; i++) { + cellHeader = row.createCell(i); + cellHeader.setCellStyle(style); + cellHeader.setCellValue(new HSSFRichTextString(headers[i])); + } + + // 遍历集合数据,产生数据行 + Iterator it = dataset.iterator(); + int index = 1; + T t; + Field[] fields; + Field field; + HSSFRichTextString richString; + Pattern p = Pattern.compile("^//d+(//.//d+)?$"); + Matcher matcher; + String fieldName; + String getMethodName; + HSSFCell cell; + Class tCls; + Method getMethod; + Object value; + String textValue; + SimpleDateFormat sdf = new SimpleDateFormat(pattern); + while (it.hasNext()) { + index++; + row = sheet.createRow(index); + t = (T) it.next(); + // 利用反射,根据JavaBean属性的先后顺序,动态调用getXxx()方法得到属性值 + fields = t.getClass().getDeclaredFields(); + for (int i = 0; i < fields.length; i++) { + cell = row.createCell(i); + cell.setCellStyle(style2); + field = fields[i]; + fieldName = field.getName(); + getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); + try { + tCls = t.getClass(); + getMethod = tCls.getMethod(getMethodName, new Class[] {}); + value = getMethod.invoke(t, new Object[] {}); + // 判断值的类型后进行强制类型转换 + textValue = null; + if (value instanceof Integer) { + cell.setCellValue((Integer) value); + } else if (value instanceof Float) { + textValue = String.valueOf((Float) value); + cell.setCellValue(textValue); + } else if (value instanceof Double) { + textValue = String.valueOf((Double) value); + cell.setCellValue(textValue); + } else if (value instanceof Long) { + cell.setCellValue((Long) value); + } + if (value instanceof Boolean) { + textValue = "是"; + if (!(Boolean) value) { + textValue = "否"; + } + } else if (value instanceof Date) { + textValue = sdf.format((Date) value); + } else { + // 其它数据类型都当作字符串简单处理 + if (value != null) { + textValue = value.toString(); + } + } + if (textValue != null) { + matcher = p.matcher(textValue); + if (matcher.matches()) { + // 是数字当作double处理 + cell.setCellValue(Double.parseDouble(textValue)); + } else { + richString = new HSSFRichTextString(textValue); + cell.setCellValue(richString); + } + } + } catch (SecurityException | NoSuchMethodException | IllegalArgumentException | IllegalAccessException | InvocationTargetException e) { + e.printStackTrace(); + } finally { + // 清理资源 + } + } + } + return workbook; + } + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/FutureReqUtil.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/FutureReqUtil.java new file mode 100644 index 000000000..3712e2e2a --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/FutureReqUtil.java @@ -0,0 +1,72 @@ +package com.example.awaysuse.util; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import lombok.extern.slf4j.Slf4j; +import uyun.whale.common.encryption.support.HttpUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +//异步调用接口请求数据 +@Slf4j +public class FutureReqUtil { + + public void getFuture(){ + + JSONArray allJsonArray = new JSONArray(); + ExecutorService executorService = Executors.newFixedThreadPool(10); + try { + // 通过异步的方式调用接口获取数据 + List allTask = new ArrayList<>(); + for (int i = 1; i <=Integer.MIN_VALUE; i++) { + allTask.add(this.queryDetailAsync(executorService)); + } + for (Future task : allTask) { + Optional.ofNullable(task.get()).ifPresent(r -> allJsonArray.addAll((JSONArray) r)); + } + allTask.clear(); + for (int i = 0; i < allJsonArray.size(); i++) { + JSONObject ticketObj = allJsonArray.getJSONObject(i); + allTask.add(executorService.submit(() -> { + String ticketId = ticketObj.getString("ticketId"); + JSONObject defaultValue = ticketObj.getJSONObject("defaultValue"); + String classfy = "meiyou"; + if (defaultValue.getString("classify") != null) { + classfy = defaultValue.getString("classify"); + } + })); + } + for (Future task : allTask) { + task.get(); + } + allTask.clear(); + log.info("结束数据详细信息"); + } catch (Exception e) { + e.printStackTrace(); + } finally { + executorService.shutdown(); + } + } + + + private Future queryDetailAsync(ExecutorService executorService){ + return executorService.submit(() -> { + String result1 = HttpUtils.doGet("请求的url", null); + JSONObject jsonObject = JSONObject.parseObject(result1); + String ticketDetail_list = jsonObject.get("ticketDetail_list").toString(); + JSONArray jsonArray = JSONArray.parseArray(ticketDetail_list); + if (jsonArray.size() <= 0){ + return null; + } + System.out.println(Thread.currentThread().getName() + " finished"); + return jsonArray; + }); + } + + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/HttpClientUtils.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/HttpClientUtils.java new file mode 100644 index 000000000..576a9c54d --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/HttpClientUtils.java @@ -0,0 +1,447 @@ +package com.example.awaysuse.util; + +import com.alibaba.fastjson.JSONObject; + +import org.apache.commons.lang.exception.ExceptionUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.HttpClient; +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.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.protocol.HTTP; +import org.apache.http.util.EntityUtils; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +public class HttpClientUtils { + + private static final Log LOG = LogFactory.getLog(HttpClientUtils.class); + + private static RequestConfig requestConfig = null; + + static { + // 设置请求和传输超时时间 + requestConfig = RequestConfig.custom().setSocketTimeout(1000 * 60 * 60).setConnectTimeout(1000 * 60 * 60).build(); + } + + /** + * post请求 + * 解决没有响应信息(是因为之前没有释放连接,导致获取不到响应) + * + * @param uri + * @param body + */ + public static Map post(String uri, JSONObject header, JSONObject body, Integer timeout) { + Map retMap = new HashMap<>(); + // 创建请求对象 + CloseableHttpClient httpClient = HttpClients.createDefault(); + HttpPost httpPost = new HttpPost(uri); + httpPost.setConfig(requestConfig); + try { + // 设置请求头信息 + httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json;charset=utf-8"); + if (header != null) { + for (String key : header.keySet()) { + Object value = header.get(key); + if (value != null && StringUtils.isNotBlank(value.toString())) { + httpPost.addHeader(key, (value == null) ? null : String.valueOf(value)); + } + } + } + LOG.info("请求头" + httpPost); + // 设置请求体信息 + String jsonstr = com.alibaba.fastjson.JSON.toJSONString(body); + StringEntity entity = new StringEntity(jsonstr, "utf-8"); + entity.setContentEncoding("UTF-8"); + entity.setContentType("application/json;charset=utf-8"); + httpPost.setEntity(entity); + + // 发出post请求 + CloseableHttpResponse response = httpClient.execute(httpPost); + //解析响应结果 + retMap.put("status", "success"); + int statusCode = response.getStatusLine().getStatusCode(); + retMap.put("statusCode", statusCode + ""); + if (statusCode == 200) { + String result = EntityUtils.toString(response.getEntity(), "utf-8"); + String loginToken = response.getFirstHeader("X-Auth-Token").getValue(); + LOG.info("返回的token" + loginToken); + retMap.put("result", result); + if (loginToken != null) { + retMap.put("loginToken", loginToken); + } + retMap.put("loginToken", loginToken); + } else if (statusCode == 201) { + String result = EntityUtils.toString(response.getEntity(), "utf-8"); + String loginToken = response.getFirstHeader("X-Auth-Token").getValue(); + LOG.info("返回的token" + loginToken); + retMap.put("result", result); + if (loginToken != null) { + retMap.put("loginToken", loginToken); + } + + } else { + retMap.put("result", EntityUtils.toString(response.getEntity(), "utf-8")); + } + + } catch (Exception e) { + LOG.error(ExceptionUtils.getFullStackTrace(e)); + retMap.put("status", "failed"); + retMap.put("exMsg", e.getLocalizedMessage()); + } finally { + httpPost.releaseConnection(); + } + return retMap; + } + + + public static Map postLogin(String uri, JSONObject header, JSONObject body, Integer timeout) { + + Map retMap = new HashMap<>(); + // 创建请求对象 + CloseableHttpClient httpClient = HttpClients.createDefault(); + HttpPost httpPost = new HttpPost(uri); + httpPost.setConfig(requestConfig); + try { + // 设置请求头信息 + httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json"); + if (header != null) { + for (String key : header.keySet()) { + Object value = header.get(key); + if (value != null && StringUtils.isNotBlank(value.toString())) { + httpPost.addHeader(key, (value == null) ? null : String.valueOf(value)); + } + } + } + LOG.info("请求头" + httpPost); + // 设置请求体信息 + String jsonstr = com.alibaba.fastjson.JSON.toJSONString(body); + StringEntity entity = new StringEntity(jsonstr, "utf-8"); + entity.setContentEncoding("UTF-8"); + entity.setContentType("application/json;charset=utf-8"); + httpPost.setEntity(entity); + + // 发出post请求 + CloseableHttpResponse response = httpClient.execute(httpPost); + //解析响应结果 + retMap.put("status", "success"); + int statusCode = response.getStatusLine().getStatusCode(); + retMap.put("statusCode", statusCode + ""); + LOG.info("返回的状态码是: " + statusCode); + if (statusCode == 201) { + String result = EntityUtils.toString(response.getEntity(), "utf-8"); + String loginToken = response.getFirstHeader("X-Auth-Token").getValue(); + LOG.info("返回的token" + loginToken); + retMap.put("result", result); + if (loginToken != null) { + retMap.put("loginToken", loginToken); + } + + } else { + retMap.put("result", EntityUtils.toString(response.getEntity(), "utf-8")); + } + + } catch (Exception e) { + LOG.error(ExceptionUtils.getFullStackTrace(e)); + retMap.put("status", "failed"); + retMap.put("exMsg", e.getLocalizedMessage()); + } finally { + httpPost.releaseConnection(); + } + return retMap; + } + + + public static Map post(String uri, JSONObject header, String body, Integer timeout) { + Map retMap = new HashMap<>(); + // 创建请求对象 + CloseableHttpClient httpClient = HttpClients.createDefault(); + HttpPost httpPost = new HttpPost(uri); + httpPost.setConfig(requestConfig); + try { + + // 设置请求头信息 + httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json;charset=utf-8"); + if (header != null) { + for (String key : header.keySet()) { + Object value = header.get(key); + if (value != null && StringUtils.isNotBlank(value.toString())) { + httpPost.addHeader(key, (value == null) ? null : String.valueOf(value)); + } + } + } + // 设置请求体信息 + StringEntity entity = new StringEntity(body, "utf-8"); + //entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); + entity.setContentEncoding("UTF-8"); + entity.setContentType("application/json"); + httpPost.setEntity(entity); + + // 设置超时时间 +/* if (timeout != null) { + httpPost.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout); + }*/ + // 发出post请求 + CloseableHttpResponse response = httpClient.execute(httpPost); + //解析响应结果 + retMap.put("status", "success"); + int statusCode = response.getStatusLine().getStatusCode(); + retMap.put("statusCode", statusCode + ""); + if (statusCode == 200) { + String result = EntityUtils.toString(response.getEntity(), "utf-8"); + retMap.put("result", result); + } else { + retMap.put("result", EntityUtils.toString(response.getEntity(), "utf-8")); + } + + } catch (Exception e) { + LOG.error(ExceptionUtils.getFullStackTrace(e)); + retMap.put("status", "failed"); + retMap.put("exMsg", e.getLocalizedMessage()); + } finally { + httpPost.releaseConnection(); + } + return retMap; + } + + + /** + * get请求 + * + * @param uri + * @param body + */ + public static Map get(String uri, JSONObject header, JSONObject body) { + return get(uri, header, body, null); + } + + /** + * get请求 + * + * @param uri + * @param body + */ + public static Map get(String uri, JSONObject header, JSONObject body, Integer timeout) { + Map retMap = new HashMap<>(); + HttpGet request = new HttpGet(uri); + try { + HttpClient client = HttpClients.createDefault();//创建HttpClient对象 + + if (header != null) { + for (String key : header.keySet()) { + Object value = header.get(key); + if (value != null && StringUtils.isNotBlank(value.toString())) { + request.addHeader(key, (value == null) ? null : String.valueOf(value)); + } + } + } + HttpResponse response = client.execute(request);//发送get请求 + int statusCode = response.getStatusLine().getStatusCode(); + + retMap.put("status", "success"); + retMap.put("statusCode", statusCode + ""); + + /**请求发送成功,并得到响应**/ + if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { + /**读取服务器返回过来的json字符串数据**/ + String strResult = EntityUtils.toString(response.getEntity(), "UTF-8"); + retMap.put("result", strResult); + } else { + if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NO_CONTENT) { + retMap.put("result", ""); + } else { + retMap.put("result", EntityUtils.toString(response.getEntity())); + } + } + } catch (IOException e) { + + LOG.info(ExceptionUtils.getFullStackTrace(e)); + retMap.put("status", "failed"); + retMap.put("exMsg", e.getLocalizedMessage()); + e.printStackTrace(); + } finally { + request.releaseConnection(); + } + return retMap; + } + + public static JSONObject httpPost(String url, JSONObject jsonParam) { + // post请求返回结果 + CloseableHttpClient httpClient = HttpClients.createDefault(); + JSONObject jsonResult = null; + HttpPost httpPost = new HttpPost(url); + // 设置请求和传输超时时间 + httpPost.setConfig(requestConfig); + try { + if (null != jsonParam) { + // 解决中文乱码问题 + StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8"); + entity.setContentEncoding("UTF-8"); + entity.setContentType("application/json"); + httpPost.setEntity(entity); + } + CloseableHttpResponse result = httpClient.execute(httpPost); + // 请求发送成功,并得到响应 + if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { + String str = ""; + try { + // 读取服务器返回过来的json字符串数据 + str = EntityUtils.toString(result.getEntity(), "utf-8"); + // 把json字符串转换成json对象 + jsonResult = JSONObject.parseObject(str); + } catch (Exception e) { + LOG.error("post请求提交失败:" + url, e); + } + } + } catch (IOException e) { + LOG.error("post请求提交失败:" + url, e); + } finally { + httpPost.releaseConnection(); + } + return jsonResult; + } + + /** + * post请求传输String参数 例如:name=Jack&sex=1&type=2 + * Content-type:application/x-www-form-urlencoded + * + * @param url url地址 + * @param strParam 参数 + * @return + */ + public static JSONObject httpPost(String url, String strParam) { + // post请求返回结果 + CloseableHttpClient httpClient = HttpClients.createDefault(); + JSONObject jsonResult = null; + HttpPost httpPost = new HttpPost(url); + httpPost.setConfig(requestConfig); + try { + if (null != strParam) { + // 解决中文乱码问题 + StringEntity entity = new StringEntity(strParam, "utf-8"); + entity.setContentEncoding("utf-8"); + entity.setContentType("application/x-www-form-urlencoded"); + httpPost.setEntity(entity); + } + CloseableHttpResponse result = httpClient.execute(httpPost); + // 请求发送成功,并得到响应 + if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { + String str = ""; + try { + // 读取服务器返回过来的json字符串数据 + str = EntityUtils.toString(result.getEntity(), "utf-8"); + // 把json字符串转换成json对象 + jsonResult = JSONObject.parseObject(str); + } catch (Exception e) { + LOG.error("post请求提交失败:" + url, e); + } + } + } catch (IOException e) { + LOG.error("post请求提交失败:" + url, e); + } finally { + httpPost.releaseConnection(); + } + return jsonResult; + } + + /** + * 发送get请求 + * + * @param url 路径 + * @return + */ + public static JSONObject httpGet(String url) { + // get请求返回结果 + JSONObject jsonResult = null; + CloseableHttpClient client = HttpClients.createDefault(); + // 发送get请求 + HttpGet request = new HttpGet(url); + request.setConfig(requestConfig); + try { + CloseableHttpResponse response = client.execute(request); + + // 请求发送成功,并得到响应 + if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { + // 读取服务器返回过来的json字符串数据 + HttpEntity entity = response.getEntity(); + String strResult = EntityUtils.toString(entity, "utf-8"); + // 把json字符串转换成json对象 + jsonResult = JSONObject.parseObject(strResult); + } else { + LOG.error("get请求提交失败:" + url); + } + } catch (IOException e) { + LOG.error("get请求提交失败:" + url, e); + } finally { + request.releaseConnection(); + } + return jsonResult; + } + + + //httpput请求 + public static Map httpPut(String uri, JSONObject header, String body, Integer timeout) { + Map retMap = new HashMap<>(); + // 创建请求对象 + CloseableHttpClient httpClient = HttpClients.createDefault(); + HttpPut httpput = new HttpPut(uri); + httpput.setConfig(requestConfig); + try { + + // 设置请求头信息 + httpput.addHeader(HTTP.CONTENT_TYPE, "application/json;charset=utf-8"); + if (header != null) { + for (String key : header.keySet()) { + Object value = header.get(key); + if (value != null && StringUtils.isNotBlank(value.toString())) { + httpput.addHeader(key, (value == null) ? null : String.valueOf(value)); + } + } + } + // 设置请求体信息 + StringEntity entity = new StringEntity(body, "utf-8"); + //entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); + entity.setContentEncoding("UTF-8"); + entity.setContentType("application/json"); + httpput.setEntity(entity); + + // 设置超时时间 +/* if (timeout != null) { + httpPost.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout); + }*/ + // 发出post请求 + CloseableHttpResponse response = httpClient.execute(httpput); + //解析响应结果 + retMap.put("status", "success"); + int statusCode = response.getStatusLine().getStatusCode(); + retMap.put("statusCode", statusCode + ""); + if (statusCode == 200) { + String result = EntityUtils.toString(response.getEntity(), "utf-8"); + retMap.put("result", result); + } else { + retMap.put("result", EntityUtils.toString(response.getEntity(), "utf-8")); + } + + } catch (Exception e) { + LOG.error(ExceptionUtils.getFullStackTrace(e)); + retMap.put("status", "failed"); + retMap.put("exMsg", e.getLocalizedMessage()); + } finally { + httpput.releaseConnection(); + } + return retMap; + } + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/MapUtils.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/MapUtils.java new file mode 100644 index 000000000..0b2bdaae4 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/MapUtils.java @@ -0,0 +1,49 @@ +package com.example.awaysuse.util; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * @Author: fengh + * @Date: 2020/7/17 14:34 + * @Description: map工具类 + */ +@Slf4j +@Component +public class MapUtils { + + private final Map map; + + public MapUtils(){ + this.map = new LinkedHashMap<>(); + } + + public MapUtils(Map map){ + this.map = map; + } + + public static MapUtils create(){ + return new MapUtils<>(new LinkedHashMap<>()); + } + + public MapUtils put(K key, V value){ + this.map.put(key, value); + return this; + } + + public Map build(){ + return map; + } + +// public static void main(String[] args) { +// //默认格式 +// Map map1 = MapUtils.create().put("name", "nicai").build(); +// //自定义格式 +// Map map2 = new MapUtils().put(1, 2).put(2, 3).build(); +// System.out.println(String.format("%s\n%s", map1, map2)); +// } + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/NullUtils.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/NullUtils.java new file mode 100644 index 000000000..2fdee0beb --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/NullUtils.java @@ -0,0 +1,28 @@ +package com.example.awaysuse.util; + +import java.util.Collection; + +/** + * @Author + * @Date 2020/10/27 12:10 + * @Description 判断是否为空 + */ +public class NullUtils { + + public static boolean isNull(Collection collection){ + return collection == null || collection.isEmpty(); + } + + public static boolean isNotNull(Collection collection){ + return collection != null && !collection.isEmpty(); + } + + public static boolean isNull(String string){ + return string == null || "".equals(string); + } + + public static boolean isNotNull(String string){ + return string != null && !"".equals(string); + } + +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/OkhttpUtil.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/OkhttpUtil.java new file mode 100644 index 000000000..2776c6904 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/OkhttpUtil.java @@ -0,0 +1,129 @@ +package com.example.awaysuse.util; + + +import com.squareup.okhttp.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.util.concurrent.TimeUnit; + +/** + * Created by er on 2018/11/16. + */ +@Component +public class OkhttpUtil { + private static final Logger logger = LoggerFactory.getLogger(OkhttpUtil.class); + public static String post(String json, String url){ + logger.info("查询的json为:{},url为:{}",json,url); + String courses=null; + //创建一个OkHttpClient对象 + OkHttpClient okHttpClient = new OkHttpClient(); + okHttpClient.setConnectTimeout(20, TimeUnit.SECONDS); + + okHttpClient.setWriteTimeout(20, TimeUnit.SECONDS); + + okHttpClient.setReadTimeout(30, TimeUnit.SECONDS); + MediaType mediaType= MediaType.parse("application/json; charset=utf-8"); + RequestBody requestBody = RequestBody.create(mediaType, json); + + //创建一个请求对象 + + Request request = new Request + .Builder() + .url(url) + .post(requestBody) + .build(); + //发送请求获取响应 + try { + Response response=okHttpClient.newCall(request).execute(); + //判断请求是否成功 + if(response.isSuccessful()){ + + courses=response.body().string(); + System.out.println("请求成功"); + }else{ + System.out.println("錯誤"+"-----"+response.code()+response.body().string()); + + } + }catch(IOException e) { + e.printStackTrace(); + } + + return courses; + } + + + + public static String get(String url){ + String courses=null; + //创建一个OkHttpClient对象 + OkHttpClient okHttpClient = new OkHttpClient(); + okHttpClient.setConnectTimeout(20, TimeUnit.SECONDS); + + okHttpClient.setWriteTimeout(20, TimeUnit.SECONDS); + + okHttpClient.setReadTimeout(30, TimeUnit.SECONDS); + //创建一个请求对象 + Request request = new Request + .Builder() + .url(url) + .build(); + //发送请求获取响应 + try { + Response response=okHttpClient.newCall(request).execute(); + //判断请求是否成功 + if(response.isSuccessful()){ + + courses=response.body().string(); + System.out.println("请求成功"); + }else{ + System.out.println("錯誤"+"-----"+response.code()+response.body().string()); + + } + }catch(IOException e) { + e.printStackTrace(); + } + + return courses; + } + + public static String postWithHead(String alretUrl,String paramBody, String cookie) { + logger.info("查询的json为:{},url为:{},param:{},cookie:{}",alretUrl,paramBody,cookie); + String courses=""; + //创建一个OkHttpClient对象 + OkHttpClient okHttpClient = new OkHttpClient(); + okHttpClient.setConnectTimeout(20, TimeUnit.SECONDS); + + okHttpClient.setWriteTimeout(20, TimeUnit.SECONDS); + + okHttpClient.setReadTimeout(30, TimeUnit.SECONDS); + MediaType mediaType= MediaType.parse("application/json; charset=utf-8"); + RequestBody requestBody = RequestBody.create(mediaType, paramBody); + + //创建一个请求对象 + + Request request = new Request + .Builder() + .url(alretUrl) + .post(requestBody).addHeader("Cookie",cookie) + .build(); + //发送请求获取响应 + try { + Response response=okHttpClient.newCall(request).execute(); + //判断请求是否成功 + if(response.isSuccessful()){ + + courses=response.body().string(); + logger.info("请求成功"); + }else{ + logger.error("錯誤"+"-----"+response.code()+response.body().string()); + + } + }catch(IOException e) { + e.printStackTrace(); + } + return courses; + } +} diff --git a/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/TimeUtil.java b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/TimeUtil.java new file mode 100644 index 000000000..a81c050b3 --- /dev/null +++ b/spring-boot-demo-alwaysuse/src/main/java/com/example/awaysuse/util/TimeUtil.java @@ -0,0 +1,253 @@ +/** + * Copyright (C), 2018-2018, jk有限公司 + * FileName: TimeUtil + * Author: 常路通 + * Date: 2018/11/16 18:38 + * Description: + * /** + * Copyright (C), 2015-2018, XXX有限公司 + * FileName: TimeUtil + * Author: chang + * Date: 2018/11/16 18:38 + * Description: + * History: + *