Java工具类

一、本人常用的HTTP Post请求的几种方式(代码)

1.HttpURLConnection

public String doPost(String URL,String jsonParams){
        OutputStreamWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        HttpURLConnection conn = null;
        try{
            URL url = new URL(URL);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            //发送POST请求必须设置为true
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //设置连接超时时间和读取超时时间
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(10000);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Accept", "application/json");
            //获取输出流
            out = new OutputStreamWriter(conn.getOutputStream());
            out.write(jsonParams);
            out.flush();
            out.close();
            //取得输入流,并使用Reader读取
            if (200 == conn.getResponseCode()){
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                String line;
                while ((line = in.readLine()) != null){
                    result.append(line);
                    System.out.println(line);
                }
            }else{
                System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                if(out != null){
                    out.close();
                }
                if(in != null){
                    in.close();
                }
            }catch (IOException ioe){
                ioe.printStackTrace();
            }
        }
        return result.toString();
    }

2、CloseableHttpClient

		<dependency>
            <groupId>org.apache.httpcomponentsgroupId>
            <artifactId>httpclientartifactId>
            <version>4.5.13version>
        dependency>
public static  String sendHttpPost(String url, JSONObject json , HashMap<String ,String > headers) {
        String jsonStr = json.toString();
        HttpPost post = new HttpPost(url);
        String response = "";
        RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(10000)
                .setConnectTimeout(10000).setSocketTimeout(10000).build();
        CloseableHttpClient client = null;
        try {
            client = HttpClients.custom().setDefaultRequestConfig(config)
                    .setSslcontext(SSLContexts.custom().loadTrustMaterial(null, (x509Certificates, s) -> true).build())
                    .setMaxConnTotal(500)
                    .setMaxConnPerRoute(200).build();
            for(Map.Entry<String,String> entry : headers.entrySet() ){
                post.addHeader(entry.getKey(), entry.getValue());
            }
            StringEntity requestBody = new StringEntity( jsonStr, "utf-8");
            post.setEntity(requestBody);
            CloseableHttpResponse httpResponse = client.execute(post);
            InputStream inStream = httpResponse.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
            StringBuilder strber = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                strber.append(line + "\n");
            }
            inStream.close();
            response = strber.toString();
        } catch (Exception e) {
            logger.info(e.getStackTrace());
        } finally {
            try {
                client.close();
            } catch (Exception e) {
                logger.info(e.getStackTrace());
            }
        }
        return response;
    }

3.HttpEntity,restTemplate

		<dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

提前注入restTemplate的bean

@Configuration
public class BeanConfig {

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        return new RestTemplate(factory);
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        //建⽴连接所⽤的时间,适⽤于⽹络状况正常的情况下,两端连接所⽤的时间。单位毫秒
        factory.setConnectTimeout(15000);
        //建⽴连接后从服务器读取到可⽤资源所⽤的时间。单位毫秒
        factory.setReadTimeout(5000);
        return factory;
    }
}

	public JsonResponse<Void> sendRecord2Server(UploadSnapRecordRequest uploadSnapRecordRequest) {
        try {
            HttpHeaders headers = new HttpHeaders();
            MimeType mimeType = MimeTypeUtils.parseMimeType("application/json");
            MediaType mediaType = new MediaType(mimeType.getType(), mimeType.getSubtype(), StandardCharsets.UTF_8);
            headers.setContentType(mediaType);
            HttpEntity<UploadSnapRecordRequest> entity = new HttpEntity<>(uploadSnapRecordRequest, headers);
            ResponseEntity<JsonResponse<Void>> resultEntity = restTemplate.exchange(ConfigService.BACKSTAGE_IMG_RUL, HttpMethod.POST, entity, new ParameterizedTypeReference<JsonResponse<Void>>() {
            });
            return resultEntity.getBody();
        } catch (Exception exception) {
            log.error("发送抓拍记录:{}时发生异常:{}", uploadSnapRecordRequest, exception.getMessage());
            return JsonResponse.fail(exception.getMessage());
        }
    }

二、MQTT连接

 		<dependency>
            <groupId>org.springframework.integrationgroupId>
            <artifactId>spring-integration-mqttartifactId>
        dependency>
package com.yf.iot.hotel.terminal.component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yf.iot.hotel.terminal.common.rest.JsonResponse;
import com.yf.iot.hotel.terminal.config.system.ConfigService;
import com.yf.iot.hotel.terminal.constant.GlobalConstant;
import com.yf.iot.hotel.terminal.hikvision.service.HkDeviceService;
import com.yf.iot.hotel.terminal.vo.BaseMqttMsg;
import com.yf.iot.hotel.terminal.vo.DeviceMsg;
import com.yf.iot.hotel.terminal.vo.FaceMsg;
import com.yf.iot.hotel.terminal.vo.VehicleMsg;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.Objects;

@Slf4j
@Service
public class MqttService {
    /**
     * 订阅主题
     */
    private final String[] topics = new String[4];
    /**
     * 消息等级,和主题数组一一对应,服务端将按照指定等级给订阅了主题的客户端推送消息
     */
    private final int[] qos = {1, 2, 2, 2};
    /**
     * 客户端对象
     */
    private MqttClient client;

    @Resource
    private HkDeviceService hkDeviceService;

    /**
     * 客户端连接服务端
     */
    public synchronized void connect() {
        try {
            String clientId = ConfigService.MQTT_CLIENT_ID;
            topics[0] = GlobalConstant.SERVER;
            topics[1] = GlobalConstant.DEVICE + clientId;
            topics[2] = GlobalConstant.VEHICLE + clientId;
            topics[3] = GlobalConstant.FACE + clientId;
            //创建MQTT客户端对象
            client = new MqttClient(ConfigService.MQTT_HOST_URL, clientId, new MemoryPersistence());
            //连接设置
            MqttConnectOptions options = new MqttConnectOptions();
            //是否清空session,设置false表示服务器会保留客户端的连接记录(订阅主题,qos),客户端重连之后能获取到服务器在客户端断开连接期间推送的消息
            //设置为true表示每次连接服务器都是以新的身份
            options.setCleanSession(false);
            //设置连接用户名
            options.setUserName(ConfigService.MQTT_USER_NAME);
            //设置连接密码
            options.setPassword(ConfigService.MQTT_PASSWORD.toCharArray());
            //设置超时时间,单位为秒
            options.setConnectionTimeout(100);
            //设置心跳时间 单位为秒,表示服务器每隔 1.5*20秒的时间向客户端发送心跳判断客户端是否在线
            options.setKeepAliveInterval(20);
            //设置遗嘱消息的话题,若客户端和服务器之间的连接意外断开,服务器将发布客户端的遗嘱信息
            options.setWill("willTopic", (clientId + "与服务器断开连接").getBytes(), 0, false);
            //设置回调
            options.setAutomaticReconnect(true);
            client.setCallback(new MqttCallbackExtended() {
                @Override
                public void connectComplete(boolean b, String s) {
                    log.info("与服务器连接成功");
                    try {
                        client.subscribe(topics, qos);
                    } catch (MqttException mqttException) {
                        log.error("与服务器连接成功,订阅topic时发生异常:{}", mqttException.getMessage());
                    }
                }

                @Override
                public void connectionLost(Throwable throwable) {
                    log.warn("与服务器断开连接");
                }

                @Override
                public void messageArrived(String s, MqttMessage mqttMessage) throws UnsupportedEncodingException {
                    String content = new String(mqttMessage.getPayload());

                    log.info("收到消息 topic:{}, content:{}", s, content);
                  
                    switch (s) {
                        case GlobalConstant.FACE:
                            handleFaceMsg(content);
                            break;
                        default:
                            log.error("未实现的主题topic:{},content:{}", type, content);
                            break;
                    }
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
                    IMqttAsyncClient client = iMqttDeliveryToken.getClient();
                    log.info("{} 发布消息成功!", client.getClientId());
                }
            });
            client.connect(options);
        } catch (MqttException e) {
            log.error("连接MQTT服务时发生异常:{}", e.getMessage());
            client = null;
        }
    }

    /**
     * 断开连接
     */
    public synchronized void disConnect() {
        try {
            if (Objects.nonNull(client)) {
                client.unsubscribe(topics);
                client.disconnect();
                client.close(true);
                client = null;
            } else {
                log.warn("连接未初始化或已销毁");
            }
        } catch (MqttException e) {
            log.error("断开MQTT服务连接时发生异常:{}", e.getMessage());
        }
    }

    /**
     * 检查连接
     */
    public synchronized void checkConnection() {
        try {
            if (Objects.isNull(client) || !client.isConnected()) {
                connect();
            }
        } catch (Exception e) {
            log.error("定时判断Mqtt是否连接时发生异常:{}", e.getMessage());
        }
    }

    /**
     * 发布消息
     *
     * @param qos      Qos
     * @param retained 是否保留
     * @param topic    主题
     * @param message  内容
     */
    public void publish(int qos, boolean retained, String topic, String message) {
        try {
            if (Objects.nonNull(client)) {
                MqttMessage mqttMessage = new MqttMessage();
                mqttMessage.setQos(qos);
                mqttMessage.setRetained(retained);
                mqttMessage.setPayload(message.getBytes());
                //主题的目的地,用于发布/订阅信息
                MqttTopic mqttTopic = client.getTopic(topic);
                //提供一种机制来跟踪消息的传递进度
                //用于在以非阻塞方式(在后台运行)执行发布是跟踪消息的传递进度
                MqttDeliveryToken token;
                //将指定消息发布到主题,但不等待消息传递完成,返回的token可用于跟踪消息的传递状态
                //一旦此方法干净地返回,消息就已被客户端接受发布,当连接可用,将在后台完成消息传递。
                token = mqttTopic.publish(mqttMessage);
                token.waitForCompletion();
            } else {
                log.warn("连接未初始化或已销毁");
            }
        } catch (MqttException e) {
            log.error("发布消息(Qos:{},Retained:{},Topic:{},Message:{})时发生异常:{}", qos, retained, topic, message, e.getMessage());
        }
    }

}

三、常用的Redis工具类

  		<dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-redisartifactId>
        dependency>

1.StringRedisTemplate

(1) 查询redis是否存在key

stringRedisTemplate.hasKey(key)

(2) 插入key-value

stringRedisTemplate.set(key,value)

(3) 插入有效期的key-value (string类型)

stringRedisTemplate.opsForValue().set(key,value,intValue,TimeUnit.MINUTES)//intValue指有效期长度,TimeUnit.MINUTES指的是分钟时间单位

(4) 删除某key

 stringRedisTemplate.delete(key)

(5) 右插入key-value (list类型)

stringRedisTemplate.opsForList().rightPush("student", JSON.toJSONString(students))

(6) 左删除key (list类型)

stringRedisTemplate.opsForList().rightPop(key);

(7) 获取value

String student = stringRedisTemplate.opsForValue().get("student");

四、逆向工程

maven插件

	<properties>
        <java.version>1.8java.version>
        <javaModelGenerator.targetProject>${basedir}/src/main/javajavaModelGenerator.targetProject>
        <sqlMapGenerator.targetProject>${basedir}/src/main/resourcessqlMapGenerator.targetProject>
        <javaClientGenerator.targetProject>${basedir}/src/main/javajavaClientGenerator.targetProject>
        <mybatis.generator.configurationFile>${basedir}/src/main/resources/generatorConfig.xmlmybatis.generator.configurationFile>
        <mybatis.generator.overwrite>truemybatis.generator.overwrite>
        <mybatis.generator.version>1.3.7mybatis.generator.version>
    properties>

 		<dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>

        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.1.4version>
        dependency>

		<build>
        <plugins>

            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>

            <plugin>
                <configuration>
                    <verbose>trueverbose>
                    <overwrite>trueoverwrite>
                    <configurationFile>src/main/resources/generator/generatorConfig.xmlconfigurationFile>
                configuration>
                <groupId>org.mybatis.generatorgroupId>
                <artifactId>mybatis-generator-maven-pluginartifactId>
                <version>1.3.7version>
                <dependencies>
                    <dependency>
                        <groupId>mysqlgroupId>
                        <artifactId>mysql-connector-javaartifactId>
                        <version>8.0.15version>
                    dependency>
                    <dependency>
                        <groupId>org.yfgroupId>
                        <artifactId>my-mybatis-generator-coreartifactId>
                        <systemPath>${project.basedir}/src/main/resources/jars/mybatis-generator-core-1.3.7.jar
                        systemPath>
                        <scope>systemscope>
                        <version>1.3.7version>
                    dependency>
                dependencies>
            plugin>
        plugins>
    build>

generatorConfig.xml


DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <context id="mysqlTables" targetRuntime="MyBatis3">
        <property name="javaFileEncoding" value="UTF-8"/>
        <property name="addColumnAnnotation" value="false"/>
        
        
        
        
        
        
        
        
        

        <plugin type="org.mybatis.generator.plugins.RowBoundsPlugin">plugin>
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin">plugin>
        <plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/>
        <plugin type="org.mybatis.generator.plugins.CaseInsensitiveLikePlugin"/>
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
        <plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin"/>


        <commentGenerator type="org.mybatis.generator.internal.DefaultCommentGenerator">
            
            
            <property name="suppressDate" value="true"/>
            
            <property name="suppressAllComments" value="false"/>
        commentGenerator>

        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://xxxxx:3306/xxx?nullCatalogMeansCurrent=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8"
                        userId="root" password="root">
        jdbcConnection>

        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        javaTypeResolver>

        <javaModelGenerator targetPackage="org.yf.entity"
                            targetProject="${javaModelGenerator.targetProject}">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>

        javaModelGenerator>

        <sqlMapGenerator targetPackage="mapper"
                         targetProject="${sqlMapGenerator.targetProject}">
            <property name="enableSubPackages" value="true"/>
        sqlMapGenerator>

        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="org.yf.mapper"
                             targetProject="${javaClientGenerator.targetProject}">
            <property name="enableSubPackages" value="false"/>

        javaClientGenerator>

      
        <table tableName="admin_role">
            <generatedKey column="id" sqlStatement="MySql" identity="true"/>
            <columnOverride column="role_state" javaType="java.lang.Integer"
                            typeHandler="org.yf.typehandler.IStateHandler"/>
        table>

    context>
generatorConfiguration>

mybatis配置


DOCTYPE configuration PUBLIC
        "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <settings>
        
        <setting name="logImpl" value="STDOUT_LOGGING"/>

        
        <setting name="cacheEnabled" value="true"/>
        <setting name="lazyLoadingEnabled" value="false"/>
        <setting name="aggressiveLazyLoading" value="true"/>
        <setting name="multipleResultSetsEnabled" value="true"/>
        
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    settings>
    
configuration>

你可能感兴趣的:(简易代码小操作,Spring,boot,java)