api
yangrc
2021-04-30 ce2db041dfb95dd9b265375dcbff22f010418de7
api
已添加21个文件
997 ■■■■■ 文件已修改
pom.xml 210 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/api/APIApplication.java 22 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/api/bean/AccessEntity.java 38 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/api/bean/ReqParams.java 29 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/api/bean/WeatherEntity.java 39 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/api/controller/AccessController.java 40 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/api/controller/WeatherController.java 81 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/api/dao/AccessDao.java 29 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/api/dao/WeatherDao.java 46 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/api/result/Msg.java 57 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/api/service/AccessService.java 64 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/api/service/WeatherService.java 55 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/api/utils/httpClient.java 144 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/resources/application.yml 58 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
target/classes/application.yml 58 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
target/maven-archiver/pom.properties 3 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst 12 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst 12 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/createdFiles.lst 补丁 | 查看 | 原始文档 | blame | 历史
target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/inputFiles.lst 补丁 | 查看 | 原始文档 | blame | 历史
target/wog-1.0-SNAPSHOT.jar.original 补丁 | 查看 | 原始文档 | blame | 历史
pom.xml
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,210 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>api</groupId>
    <artifactId>api</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.4</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.6</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>
        <!-- mybatis -->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <!--自动配置-->
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.13</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.6</version>
        </dependency>
        <!--分页插件-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.msgpack/msgpack -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.4</version>
        </dependency>
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.6.0</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>18.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Greenwich.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>http://repo.spring.io/libs-snapshot-local</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>http://repo.spring.io/libs-milestone-local</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>http://repo.spring.io/libs-release-local</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>http://repo.spring.io/libs-snapshot-local</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>http://repo.spring.io/libs-milestone-local</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
src/main/java/api/APIApplication.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,22 @@
package api;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
 * @program: wog
 * @description:
 * @author: YSS
 * @create: 2020-09-25 11:36
 **/
@SpringBootApplication
@MapperScan(basePackages = "api.dao")
public class APIApplication {
    public static void main(String[] args) {
        SpringApplication.run(APIApplication.class,args);
    }
}
src/main/java/api/bean/AccessEntity.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,38 @@
package api.bean;
import lombok.Data;
import java.util.Date;
/**
 * @program: wog
 * @description:
 * @author: YSS
 * @create: 2020-09-25 11:49
 **/
@Data
public class AccessEntity {
    private Long userId;
    private Long accessId;
    private String accessKey;
    private String accessSercet;
    private String accessToken;
    private Date updateTime;
    @Override
    public String toString() {
        return "AccessEntity{" +
                "userId=" + userId +
                ", accessId=" + accessId +
                ", accessKey='" + accessKey + '\'' +
                ", accessSercet='" + accessSercet + '\'' +
                ", accessToken='" + accessToken + '\'' +
                '}';
    }
}
src/main/java/api/bean/ReqParams.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,29 @@
package api.bean;
import lombok.Data;
import java.io.Serializable;
/**
 * @program: wog
 * @description:
 * @author: YSS
 * @create: 2020-09-25 15:11
 **/
@Data
public class ReqParams implements Serializable {
    // token
    private String accessToken;
    // å½“前页码
    private Integer page;
    // å½“前页面条数
    private Integer limit;
    private Long lightId;
    private Long[] lightIds;
    private String mac;
}
src/main/java/api/bean/WeatherEntity.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,39 @@
package api.bean;
import lombok.Data;
import java.util.Date;
/**
 * @program: wog
 * @description: çŽ¯å¢ƒç›‘æµ‹
 * @author: YSS
 * @create: 2020-09-26 16:26
 **/
@Data
public class WeatherEntity {
    private Long dwStreetlightId;
    private String dwStreetlightName;
    private Double dwTemperature;
    private Double dwHumidity;
    private Double dwPm25;
    private Double dwPm10;
    private Double dwEch2o;
    private Double dwEco2;
    private Double dwWindSpeed;
    private Double dwTvoc;
    private Double dwBrightness;
    private String dwCreateTime;
}
src/main/java/api/controller/AccessController.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,40 @@
package api.controller;
import api.bean.AccessEntity;
import api.result.Msg;
import api.service.AccessService;
import com.google.common.util.concurrent.RateLimiter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/**
 * @program: wog
 * @description:
 * @author: YSS
 * @create: 2020-09-25 14:24
 **/
@RestController
@RequestMapping("/access")
public class AccessController {
    @Autowired
    private AccessService accessService;
    RateLimiter rateLimiter = RateLimiter.create(10);
    @RequestMapping(value = "/get",method = RequestMethod.POST)
    public Msg get(@RequestBody AccessEntity accessEntity) {
        rateLimiter.acquire(1);
        return accessService.getAccessToken(accessEntity);
    }
}
src/main/java/api/controller/WeatherController.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,81 @@
package api.controller;
import api.bean.ReqParams;
import api.bean.WeatherEntity;
import api.result.Msg;
import api.service.AccessService;
import api.service.WeatherService;
import com.github.pagehelper.PageInfo;
import com.google.common.util.concurrent.RateLimiter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @program: wog
 * @description:
 * @author: YSS
 * @create: 2020-09-26 16:28
 **/
@RestController
@RequestMapping("/weather")
public class WeatherController {
    @Autowired
    private AccessService accessService;
    @Autowired
    private WeatherService weatherService;
    RateLimiter rateLimiter = RateLimiter.create(10.0);
    @RequestMapping(value = "/list",method = RequestMethod.POST)
    public Msg list(@RequestBody ReqParams reqParams){
        rateLimiter.acquire(1);
        if(reqParams.getLimit() > 50){
            return Msg.error("limit exception");
        }
        Long userId = accessService.getUserId(reqParams.getAccessToken());
        if(userId == null) {
            return Msg.error("server exception");
        }
        PageInfo<WeatherEntity> info = weatherService.selectList(userId, reqParams);
        Map data = new HashMap();
        data.put("total",info.getTotal());
        data.put("list",info.getList());
        return Msg.ok().put("data",data);
    }
    @RequestMapping(value = "/info",method = RequestMethod.POST)
    public Msg info(@RequestBody ReqParams reqParams){
        rateLimiter.acquire(1);
        if(reqParams.getLimit() > 50){
            return Msg.error("limit exception");
        }
        Long userId = accessService.getUserId(reqParams.getAccessToken());
        if(userId == null) {
            return Msg.error("server exception");
        }
        PageInfo<WeatherEntity> info = weatherService.selectByStreetlightId(reqParams);
        Map data = new HashMap();
        data.put("total",info.getTotal());
        data.put("list",info.getList());
        return Msg.ok().put("data",data);
    }
}
src/main/java/api/dao/AccessDao.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,29 @@
package api.dao;
import api.bean.AccessEntity;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;
/**
 * @program: wog
 * @description:
 * @author: YSS
 * @create: 2020-09-25 14:44
 **/
@Mapper
@Repository
public interface AccessDao {
    @Select("select * from wog_user_access where access_key = #{accessKey} limit 1")
    AccessEntity selectAccessEntityByKey(@Param("accessKey") String accessKey);
    @Update("update wog_user_access set access_token = #{accessToken}, update_time = #{updateTime} where access_key = #{accessKey}")
    void update(AccessEntity accessEntity);
    @Select("select user_id from wog_user_access where access_token = #{token}")
    Long selectUserIdByToken(@Param("token")String accessToken);
    @Select("select role_id from sys_user_role where user_id = #{userId}")
    Long selectRoleIdByUserId(@Param("userId") Long userId);
}
src/main/java/api/dao/WeatherDao.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,46 @@
package api.dao;
import api.bean.WeatherEntity;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
 * @program: wog
 * @description:
 * @author: YSS
 * @create: 2020-09-26 16:44
 **/
@Mapper
@Repository
public interface WeatherDao {
    @Results(id = "WeatherMap",value = {
            @Result(property = "dwStreetlightId",column = "streetlight_id"),
            @Result( property = "dwStreetlightName",column = "streetlight_name"),
            @Result(property="dwTemperature",column="temperature"),
            @Result(property="dwHumidity" ,column="humidity"),
            @Result(property="dwPm25" ,column="pm25"),
            @Result(property="dwPm10" ,column="pm10"),
            @Result(property="dwEch2o" ,column="ech2o"),
            @Result(property="dwEco2" ,column="eco2"),
            @Result(property="dwWindSpeed" ,column="wind_speed"),
            @Result(property="dwTvoc" ,column="tvoc"),
            @Result(property="dwBrightness" ,column="brightness"),
            @Result(property="dwCreateTime" ,column="create_time"),
    })
    @Select("SELECT pole_streetlight.streetlight_name,pole_sensor.* FROM pole_sensor  LEFT JOIN pole_streetlight  ON pole_streetlight.streetlight_id = pole_sensor.streetlight_id WHERE sensor_id IN ( SELECT max(sensor_id) FROM pole_sensor GROUP BY streetlight_id) ")
    List<WeatherEntity> selectAll();
    @ResultMap(value = "WeatherMap")
    @Select("SELECT p1.streetlight_name,p2.* FROM pole_streetlight p1 LEFT JOIN pole_sensor p2 ON p1.streetlight_id = p2.streetlight_id WHERE sensor_id IN (SELECT max(sensor_id) FROM pole_sensor WHERE streetlight_id IN ( SELECT streetlight_id FROM pole_user_streetlight WHERE company_id = (SELECT company_id FROM sys_user_company WHERE user_id = #{userId}))GROUP BY streetlight_id) ")
    List<WeatherEntity> selectByCompany(Long userId);
    @ResultMap(value = "WeatherMap")
    @Select("SELECT p1.streetlight_name,p2.* FROM pole_streetlight p1 LEFT JOIN pole_sensor p2 ON p1.streetlight_id = p2.streetlight_id WHERE sensor_id IN ( SELECT max(sensor_id)  FROM pole_sensor WHERE streetlight_id IN ( SELECT streetlight_id FROM pole_user_streetlight WHERE user_id = #{userId}) GROUP BY streetlight_id) ")
    List<WeatherEntity> selectByUserId(Long userId);
    @ResultMap(value = "WeatherMap")
    @Select(" SELECT pole_sensor.*, pole_streetlight.streetlight_name from pole_sensor LEFT JOIN pole_streetlight ON pole_sensor.streetlight_id = pole_streetlight.streetlight_id WHERE pole_streetlight.streetlight_id = #{streetLightId} ORDER BY pole_sensor.create_time DESC")
    List<WeatherEntity> selectByStreetlightId(Long lightId);
}
src/main/java/api/result/Msg.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,57 @@
package api.result;
import org.apache.http.HttpStatus;
import java.util.HashMap;
import java.util.Map;
/**
 * @program: wog
 * @description:
 * @author: YSS
 * @create: 2020-09-25 14:25
 **/
public class Msg extends HashMap<String,Object> {
    public Msg() {
        put("code", 200);
        put("msg", "success");
    }
    public static Msg error() {
        return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常,请联系管理员");
    }
    public static Msg error(String msg) {
        return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
    }
    public static Msg error(int code, String msg) {
        Msg msg1 = new Msg();
        msg1.put("code", code);
        msg1.put("msg", msg);
        return msg1;
    }
    public static Msg ok(String msg) {
        Msg r = new Msg();
        r.put("msg", msg);
        return r;
    }
    public static Msg ok(Map<String, Object> map) {
        Msg r = new Msg();
        r.putAll(map);
        return r;
    }
    public static Msg ok() {
        return new Msg();
    }
    public Msg put(String key, Object value) {
        super.put(key, value);
        return this;
    }
}
src/main/java/api/service/AccessService.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,64 @@
package api.service;
import api.bean.AccessEntity;
import api.dao.AccessDao;
import api.result.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.UUID;
/**
 * @program: wog
 * @description:
 * @author: YSS
 * @create: 2020-09-25 14:34
 **/
@Service
public class AccessService {
    private static final Long OUT_EXPRESS_TIME = (long)7 * 1000 * 60 * 60 * 24;
    @Autowired
    private AccessDao accessDao;
    public void update(AccessEntity accessEntity) {
        accessDao.update(accessEntity);
    }
    public AccessEntity selectAccessEntityByKey(String accessKey) {
        return accessDao.selectAccessEntityByKey(accessKey);
    }
    public Long getUserId(String accessToken) {
        return accessDao.selectUserIdByToken(accessToken);
    }
    public Long getRoleId(Long userId) {
        return accessDao.selectRoleIdByUserId(userId);
    }
    public Msg getAccessToken(AccessEntity accessEntity) {
        AccessEntity accessData = selectAccessEntityByKey(accessEntity.getAccessKey());
        if(null == accessData) {
            return Msg.error("user no exist");
        }
        if(!accessData.getAccessSercet().equals(accessEntity.getAccessSercet())) {
            return Msg.error("secret mistake");
        }
        if(new Date().getTime() - accessData.getUpdateTime().getTime() > OUT_EXPRESS_TIME) {
            accessData.setAccessToken(UUID.randomUUID().toString());
            accessData.setUpdateTime(new Date());
            update(accessData);
        }
        return Msg.ok().put("accessToken",accessData.getAccessToken());
    }
}
src/main/java/api/service/WeatherService.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,55 @@
package api.service;
import api.bean.ReqParams;
import api.bean.WeatherEntity;
import api.dao.WeatherDao;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
 * @program: wog
 * @description:
 * @author: YSS
 * @create: 2020-09-26 16:38
 **/
@Service
public class WeatherService {
    @Autowired
    private AccessService accessService;
    @Autowired
    private WeatherDao weatherDao;
    public PageInfo<WeatherEntity> selectList(Long userId, ReqParams reqParams) {
        Long roleId = accessService.getRoleId(userId);
        if (roleId == null || roleId == 0) {
            return null;
        }
        List<WeatherEntity> list = null;
        if (roleId.longValue() == 1) {
            PageHelper.startPage(reqParams.getPage(), reqParams.getLimit());
            list = weatherDao.selectAll();
        } else if (roleId.longValue() == 2) {
            PageHelper.startPage(reqParams.getPage(), reqParams.getLimit());
            list = weatherDao.selectByCompany(userId);
        } else if (roleId.longValue() == 3) {
            PageHelper.startPage(reqParams.getPage(), reqParams.getLimit());
            list = weatherDao.selectByUserId(userId);
        }
        PageInfo<WeatherEntity> page = new PageInfo<>(list);
        return page;
    }
    public PageInfo<WeatherEntity> selectByStreetlightId(ReqParams reqParams) {
        PageHelper.startPage(reqParams.getPage(),reqParams.getLimit());
        List<WeatherEntity> list = weatherDao.selectByStreetlightId(reqParams.getLightId());
        PageInfo<WeatherEntity> page = new PageInfo<>(list);
        return page;
    }
}
src/main/java/api/utils/httpClient.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,144 @@
package api.utils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.Map.Entry;
/**
 * @program: api
 * @description:
 * @author: YSS
 * @create: 2020-09-03 14:13
 **/
public class httpClient {
        public static String doGet(String url) {
            CloseableHttpClient httpClient = null;
            CloseableHttpResponse response = null;
            String result = "";
            try {
                // é€šè¿‡å€é»˜è®¤é…ç½®åˆ›å»ºä¸€ä¸ªhttpClient实例
                httpClient = HttpClients.createDefault();
                // åˆ›å»ºhttpGet远程连接实例
                HttpGet httpGet = new HttpGet(url);
                // è®¾ç½®è¯·æ±‚头信息,鉴权
                httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
                // è®¾ç½®é…ç½®è¯·æ±‚参数
                RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// è¿žæŽ¥ä¸»æœºæœåŠ¡è¶…æ—¶æ—¶é—´
                        .setConnectionRequestTimeout(35000)// è¯·æ±‚è¶…æ—¶æ—¶é—´
                        .setSocketTimeout(60000)// æ•°æ®è¯»å–è¶…æ—¶æ—¶é—´
                        .build();
                // ä¸ºhttpGet实例设置配置
                httpGet.setConfig(requestConfig);
                // æ‰§è¡Œget请求得到返回对象
                response = httpClient.execute(httpGet);
                // é€šè¿‡è¿”回对象获取返回数据
                HttpEntity entity = response.getEntity();
                // é€šè¿‡EntityUtils中的toString方法将结果转换为字符串
                result = EntityUtils.toString(entity);
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // å…³é—­èµ„源
                if (null != response) {
                    try {
                        response.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != httpClient) {
                    try {
                        httpClient.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return result;
        }
        public static String doPost(String url, Map<String, Object> paramMap) {
            CloseableHttpClient httpClient = null;
            CloseableHttpResponse httpResponse = null;
            String result = "";
            // åˆ›å»ºhttpClient实例
            httpClient = HttpClients.createDefault();
            // åˆ›å»ºhttpPost远程连接实例
            HttpPost httpPost = new HttpPost(url);
            // é…ç½®è¯·æ±‚参数实例
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// è®¾ç½®è¿žæŽ¥ä¸»æœºæœåŠ¡è¶…æ—¶æ—¶é—´
                    .setConnectionRequestTimeout(35000)// è®¾ç½®è¿žæŽ¥è¯·æ±‚è¶…æ—¶æ—¶é—´
                    .setSocketTimeout(60000)// è®¾ç½®è¯»å–数据连接超时时间
                    .build();
            // ä¸ºhttpPost实例设置配置
            httpPost.setConfig(requestConfig);
            // è®¾ç½®è¯·æ±‚头
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
            // å°è£…post请求参数
            if (null != paramMap && paramMap.size() > 0) {
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                // é€šè¿‡map集成entrySet方法获取entity
                Set<Entry<String, Object>> entrySet = paramMap.entrySet();
                // å¾ªçŽ¯éåŽ†ï¼ŒèŽ·å–è¿­ä»£å™¨
                Iterator<Entry<String, Object>> iterator = entrySet.iterator();
                while (iterator.hasNext()) {
                    Entry<String, Object> mapEntry = iterator.next();
                    nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
                }
                // ä¸ºhttpPost设置封装好的请求参数
                try {
                    httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            try {
                // httpClient对象执行post请求,并返回响应参数对象
                httpResponse = httpClient.execute(httpPost);
                // ä»Žå“åº”对象中获取响应内容
                HttpEntity entity = httpResponse.getEntity();
                result = EntityUtils.toString(entity);
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // å…³é—­èµ„源
                if (null != httpResponse) {
                    try {
                        httpResponse.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != httpClient) {
                    try {
                        httpClient.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return result;
        }
}
src/main/resources/application.yml
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,58 @@
server:
  port: 9090
  servlet:
    context-path: /api
mybatis:
  configuration:
    map-underscore-to-camel-case: true
spring:
  datasource:
    url: jdbc:mysql://47.106.172.9:2512/machine?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
    username: root
    password: Zhxm2512209
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      #初始化大小
      initialSize: 5
      #最小值
      minIdle: 5
      #最大值
      maxActive: 20
      #最大等待时间,配置获取连接等待超时,时间单位都是毫秒ms
      maxWait: 60000
      #配置间隔多久才进行一次检测,检测需要关闭的空闲连接
      timeBetweenEvictionRunsMillis: 60000
      #配置一个连接在池中最小生存的时间
      minEvictableIdleTimeMillis: 300000
      validationQuery: SELECT 1 FROM DUAL
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      poolPreparedStatements: true
      # é…ç½®ç›‘控统计拦截的filters,去掉后监控界面sql无法统计,
      #'wall'用于防火墙,SpringBoot中没有log4j,我改成了log4j2
      filters: stat,wall,log4j2
      #最大PSCache连接
      maxPoolPreparedStatementPerConnectionSize: 20
      useGlobalDataSourceStat: true
      # é€šè¿‡connectProperties属性来打开mergeSql功能;慢SQL记录
      connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
      # é…ç½®StatFilter
      web-stat-filter:
        #默认为false,设置为true启动
        enabled: true
        url-pattern: "/*"
        exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"
      #配置StatViewServlet
      stat-view-servlet:
        url-pattern: "/druid/*"
        #是否可以重置
        reset-enable: true
        #启用
        enabled: true
target/classes/application.yml
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,58 @@
server:
  port: 9090
  servlet:
    context-path: /api
mybatis:
  configuration:
    map-underscore-to-camel-case: true
spring:
  datasource:
    url: jdbc:mysql://47.106.172.9:2512/machine?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
    username: root
    password: Zhxm2512209
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      #初始化大小
      initialSize: 5
      #最小值
      minIdle: 5
      #最大值
      maxActive: 20
      #最大等待时间,配置获取连接等待超时,时间单位都是毫秒ms
      maxWait: 60000
      #配置间隔多久才进行一次检测,检测需要关闭的空闲连接
      timeBetweenEvictionRunsMillis: 60000
      #配置一个连接在池中最小生存的时间
      minEvictableIdleTimeMillis: 300000
      validationQuery: SELECT 1 FROM DUAL
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      poolPreparedStatements: true
      # é…ç½®ç›‘控统计拦截的filters,去掉后监控界面sql无法统计,
      #'wall'用于防火墙,SpringBoot中没有log4j,我改成了log4j2
      filters: stat,wall,log4j2
      #最大PSCache连接
      maxPoolPreparedStatementPerConnectionSize: 20
      useGlobalDataSourceStat: true
      # é€šè¿‡connectProperties属性来打开mergeSql功能;慢SQL记录
      connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
      # é…ç½®StatFilter
      web-stat-filter:
        #默认为false,设置为true启动
        enabled: true
        url-pattern: "/*"
        exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"
      #配置StatViewServlet
      stat-view-servlet:
        url-pattern: "/druid/*"
        #是否可以重置
        reset-enable: true
        #启用
        enabled: true
target/maven-archiver/pom.properties
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,3 @@
version=1.0-SNAPSHOT
groupId=wog
artifactId=wog
target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,12 @@
api\dao\AccessDao.class
api\service\WeatherService.class
api\service\AccessService.class
api\result\Msg.class
api\utils\httpClient.class
api\bean\AccessEntity.class
api\APIApplication.class
api\bean\ReqParams.class
api\dao\WeatherDao.class
api\controller\WeatherController.class
api\bean\WeatherEntity.class
api\controller\AccessController.class
target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,12 @@
D:\api\src\main\java\api\bean\ReqParams.java
D:\api\src\main\java\api\controller\WeatherController.java
D:\api\src\main\java\api\dao\AccessDao.java
D:\api\src\main\java\api\service\WeatherService.java
D:\api\src\main\java\api\service\AccessService.java
D:\api\src\main\java\api\APIApplication.java
D:\api\src\main\java\api\bean\WeatherEntity.java
D:\api\src\main\java\api\dao\WeatherDao.java
D:\api\src\main\java\api\result\Msg.java
D:\api\src\main\java\api\bean\AccessEntity.java
D:\api\src\main\java\api\controller\AccessController.java
D:\api\src\main\java\api\utils\httpClient.java
target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/createdFiles.lst
target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/inputFiles.lst
target/wog-1.0-SNAPSHOT.jar.original
Binary files differ