微服務內部通信之白名單


微服務通信的方式有很多,有的用Socket,也有用一些HTTP客戶端工具類,還有的有現成的組件如SpringCloud Open-Feign等。

這些共同點都是通信。

不同服務之間的通信涉及很多方面,比分說內網訪問,外網不能訪問等。

那么微服務如何實現內部通信呢(這里說的是內網通信,外網不能訪問)?

核心代碼如下(采用攔截器機制):
代碼中的if-else那段代碼可以放在數據庫,也可以存NoSQL或者配置文件之類的。

public class IPInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());

        if ("127.0.0.1".equals(ip)) {
            System.out.println("內部IP放行");
            return true;
        } else {
            System.out.println("外部IP禁止訪問");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", "403");
            jsonObject.put("msg", "Not Allowed");

            response.getWriter().append(jsonObject.toJSONString());
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

采用攔截器機制后,對應的feign組件URL指向改為如下即可(主要是@FeignClient屬性中的url):

@FeignClient(contextId = "userApiService", value = ServiceNameConstants.BLOG_SERVICE, url = "http://127.0.0.1:2020")
@RestController
public interface UserApiService {

    @GetMapping("/blog_user/list")
    String queryUserList();
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM