springMVC+naco实现跨服务接口调用

spring 直接使用nacos中的api,不能使用SpringCloud提供的feign和restTemplate接口服务,此处采用的是原始的http方式。
上干活:

1.pom

        <dependency>
            <groupId>com.alibaba.nacos</groupId>
            <artifactId>nacos-spring-context</artifactId>
            <version>0.3.6</version>
        </dependency>

2. NacosConfiguration.java

package com.leinovo.mqm.web.ms;

import com.alibaba.nacos.api.annotation.NacosProperties;
import com.alibaba.nacos.spring.context.annotation.discovery.EnableNacosDiscovery;
import org.springframework.context.annotation.Configuration;

/**
 * @Author: leimin
 * @Description: new class
 * @Date: 2020/6/9 16:09
 * @Version: 1.0
 */
@Configuration
@EnableNacosDiscovery(globalProperties = @NacosProperties(serverAddr = "11.22.33.44:8848"))
public class NacosConfiguration {

}

3. 使用nacos,并使用http实现api跨服务调用

package com.lenovo.mqm.utility;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.lenovo.mqm.entity.Mqmid;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: leimin
 * @Description: new class
 * @Date: 2020/6/10 9:41
 * @Version: 1.0
 */
@Component
public class PortalUserUtil {

    /**
     * nacos服务类
     */
    @NacosInjected
    private NamingService namingService;

    @Resource
    private HttpUtil httpUtil;

    /**
     * cacheMap
     */
    private Map<String, Instance> userCacheMap = new HashMap<>(Constants.SIXTEEN);

    /**
     * 通过服务名称用户的sessionId获取当前登录的服务对象
     *
     * @param sessionId 随机数
     * @return 重新封装后的额服务对象
     * @throws NacosException nacos异常
     */
    public Mqmid getPortalUser(String sessionId) throws NacosException {

        String serviceName = Constants.AUTH_NAME;
        Instance instance = userCacheMap.get(serviceName);
        if (instance == null) {
            List<Instance> allInstances = namingService.getAllInstances(serviceName);
            if (CollectionUtils.isEmpty(allInstances)) {
                return null;
            }
            // 只有一个,取第一个
            instance = allInstances.get(0);

            // 维护缓存,只保存10个
            keepSize();
            userCacheMap.put(serviceName, instance);
        }

        String ip = instance.getIp();
        int port = instance.getPort();
        String addr = "http://" + ip + ":" + port + "";
        String url = addr + "/api/xxx/?sessionId=" + sessionId;

        Map<String, String> header = new HashMap<>(Constants.SIXTEEN);
        header.put("Content-Type", "application/json");
        header.put("Accept", "*/*");


		//  此处见下一点:httpUtil
        String baseStr = httpUtil.doPost(url, header, "");

        JSONObject jsonObject = JSONObject.parseObject(baseStr);
        JSONObject data = jsonObject.getJSONObject("data");
        if (data == null) {
            return null;
        }

        Mqmid mqmid = new Mqmid();
        mqmid.setId(data.getLong("id"));
        mqmid.setAddress(data.getString("address"));
        mqmid.setCreated(data.getLong("runtimeCreated"));
        mqmid.setDepartment(data.getString("origin"));
        mqmid.setEmail(data.getString("email"));
        mqmid.setHashing(data.getString("hashing"));
        mqmid.setPhone(data.getString("phone"));
        mqmid.setState(data.getInteger("state"));
        mqmid.setUsername(data.getString("username"));

        return mqmid;
    }

    /**
     * 维护缓存的大小
     */
    private void keepSize() {

        if (userCacheMap.size() < Constants.TWELVE) {
            return;
        }

        Map<String, Instance> newMap = new HashMap<>(Constants.SIXTEEN);
        int i = 0;
        for (Map.Entry<String, Instance> entry : userCacheMap.entrySet()) {

            if (entry.getValue() == null || StringUtils.isEmpty(entry.getKey())) {
                continue;
            }

            newMap.put(entry.getKey(), entry.getValue());
            i++;

            if (i > Constants.TEN) {
                break;
            }
        }

        userCacheMap.clear();
        userCacheMap = newMap;
    }

4. httpUtil

package com.didispace.springboothello.controller;


import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

/**
 * Http请求工具类
 * @author weihong.zhu
 */
@Component
public class HttpUtil {

    /**
     * 设置连接超时时间,20000,消除魔术数字
     */
    private static final int TWOTHOUSAND = 20000;

    /**
     * 发送post请求
     *
     * @param url    请求路径
     * @param header 请求头
     * @param body   请求体
     * @return String
     */
    public String doPost(String url, Map<String, String> header, String body) {

        String result = "";
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            // 设置 url
            URL realUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            // 设置 header
            for (Map.Entry<String, String> entry: header.entrySet()) {
                connection.setRequestProperty(entry.getKey(), entry.getValue());
            }
            // 设置请求 body
            connection.setDoOutput(true);
            connection.setDoInput(true);

            //设置连接超时和读取超时时间
            connection.setConnectTimeout(TWOTHOUSAND);
            connection.setReadTimeout(TWOTHOUSAND);
            try {
                out = new PrintWriter(connection.getOutputStream());
                // 保存body
                out.print(body);
                // 发送body
                out.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                // 获取响应body
                in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
            //return null;
        }
        return result;
    }

    /**
     * 发送get请求
     *
     * @param url    请求路径
     * @param header 请求头
     * @return String
     */
    public String doGet(String url, Map<String, String> header) {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try {
            // 设置 url
            URL realUrl = new URL(url);
            URLConnection connection = realUrl.openConnection();
            // 设置 header
            for (Map.Entry<String, String> entry: header.entrySet()) {
                connection.setRequestProperty(entry.getKey(), entry.getValue());
            }
            // 设置请求 body
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return result.toString();
    }
}

你可能感兴趣的:(springMVC,nacos,springMVC+naco,实现跨服务接口调用)