LoginServiceImpl.java 5.8 KB
package com.tianbo.messagebus.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tianbo.messagebus.model.Auth;
import com.tianbo.messagebus.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    /** 账户登录地址
     */
    @Value("${message-bus.url.login-url}")
    private String LOGIN_URL;
    /**
     * 账号名
     */
    @Value("${message-bus.auth.username}")
    private String USER_NAME;
//    private static final String USER_NAME = "HYYW";
    /**
     * 登陆密码
     */
    @Value("${message-bus.auth.password}")
    private String USER_PASS;

    /**
     * 心跳接口地址
     */
    @Value("${message-bus.url.hearbit-url}")
    private  String HEARTBEAT_URL;
    /**
     * 心跳间隔时间 单位S
     */
    @Value("${message-bus.heartbit-interval}")
    private int HEARTBIT_INTERVAL;

    /**
     * HTTP请求框架
     */
    @Resource
    private RestTemplate restTemplate;

    @Override
    public void login() {
        try {
            /*
             * 发起HTTP 登录请求
             * 登录接口的请求头为application/x-www-form-urlencoded
             */
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            /*
             * 请求参数
             */
            MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
            params.add("username", USER_NAME);
            params.add("password", USER_PASS);
            log.info("[LOGIN]-登录用户:[{}],登录密码:[{}]",USER_NAME,USER_PASS);

            HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(params, headers);

            /*
             * 提交HTTP访问,获取返回信息
             */
            ResponseEntity<String> response = restTemplate.postForEntity(LOGIN_URL, request, String.class);
            //  输出结果
            log.info(response.getBody());


        /*
            校验是否登录成功
         */
            if (response.getStatusCode().equals(HttpStatus.OK)) {
                /**
                 * 从返回信息中确定是否登录成功,并取得token
                 * 返回格式
                 * {
                 "code":200,
                 "data":{
                 "account":"yangyucheng",
                 "token":"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI2MCIsIm5hbWUiOiLmnajnjonmiJDmtYvor5UiLCJpZCI6NjAsImlhdCI6MTYxNzM0ODM3MiwiYWNjb3VudCI6Inlhbmd5dWNoZW5nIn0.ElAs7BtV1tu6ApQXuPXzgXUgvja76bjEb-zxqhUON48"
                 },
                 "message":"success",
                 "success":true,
                 "time":20210402152612604
                 }
                 */
                JSONObject resJson = JSON.parseObject(response.getBody());
                JSONObject resData = resJson.getJSONObject("data");
                String resCode  = resJson.getString("code");



            /*
              校验并获取登陆成功后返回的token
             */
                String authToken = resData.getString("token");
                if ("200".equals(resCode) && StringUtils.hasLength(authToken) && authToken.length() > 10) {
                    Auth.LOGIN_STATUS = true;

                    //设置请求头部Authorization为token, token的类型为Bearer
                    Auth.TOKEN = authToken;

                    log.info("登录成功:token=[{}]",Auth.TOKEN);
                }else {
                    log.error("登录失败");
                }
            } else {
                log.error("登录失败");
            }

        } catch (Exception e) {
            log.error("登录失败->{}",e.toString());
        }
    }

    @Override
    public void heartBit() {
        if (StringUtils.hasLength(Auth.TOKEN) && Auth.LOGIN_STATUS){
            /*
             * 发起HTTP 登录请求
             * 登录接口的请求头为application/x-www-form-urlencoded
             */
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            /*
             * 设置获取到的token到头部信息Authorization节点中
             */
            headers.setBearerAuth(Auth.TOKEN);

            /*
             * 心跳接口无参数,访问接口即可
             */
            MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();

            HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(params, headers);

            /*
             * 提交HTTP访问,获取返回信息
             */
            ResponseEntity<String> response = restTemplate.postForEntity(HEARTBEAT_URL, request, String.class);

            //  输出结果
            log.debug(response.getBody());

            if (response.getStatusCode().equals(HttpStatus.OK)) {
                log.debug("[HEART-BIT]-心跳成功");
            } else {
                log.error("[HEART-BIT-ERR]-心跳失败");
            }
        }else {
            log.error("[HEART-BIT-ERR]-未登录,心跳失败");
        }
    }


    @Scheduled(fixedRate = 9000)
    @Override
//    @Async("HEART-POOL")
    public  void startHeartBit() {
        log.info("[LOGINED]-开始心跳");
        heartBit();
    }
}