我用Squid为Java http请求设置代理

什么是代理服务器

代理服务器充当你和Internet之间的网关,就像一个中间人。它实际上是一个中间服务器,可以将用户与它们游览的网站区分开。

如果你使用了代理服务器,那么网络流量会通过代理服务器流向你请求的地址。然后该请求通过同一台代理服务器返回,然后代理服务器将从网站接收到的数据转发给你。

当然如果仅仅是这样,也没什么必要使用代理服务器,我们直接访问网站岂不更美?

现在代理服务器的功能远不只是转发Web请求,而这一切都是为了保证数据安全和网络性能。代理服务器充当防火墙和Web筛选器,提供共享的网络连接,并缓存数据以加快常见请求的速度。
而且还可以保护用户和内部网络以免收到外部Internet的不良影响。

Java如何使用代理服务器

java 有两种方式可以设置代理服务器

如何设置

  1. 通过命令行选项进行设置
java -Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080 -Dhttp.nonProxyHosts="localhost|host.example.com" test.jar 

所有http连接都将通过webcache.example.com上的代理服务器在端口8080上监听(如果不指定端口默认是80),此外,连接到localhost或host.example.com时将不使用代理。

  1. 通过System.setProperty(String,String)方法
// 设置代理
System.setProperty("http.proxyHost", "webcache.example.com");
System.setProperty("http.proxyPort", "8080");


// 下一个连接将会使用代理
URL url = new URL("http://java.example.org/");
InputStream in = url.openStream();

// 清除代理
System.clearProperty("http.proxyHost");

// 从现在开始,http连接将直接完成而不再使用代理

参数说明

  1. http.proxyHost : 代理服务器主机名
  2. http.proxyPort : 端口号,默认是80
  3. https.proxyHost : https代理服务器主机名
  4. https.proxyPort: 代理端口号,默认是443
  5. http.nonProxyHosts : 指定绕过代理的主机列表,使用 | 分割的模式列表,可以以通配符 * 开头或者结尾,任何匹配这些模式之一的主机都将通过直接连接而不是通过代理访问。该设置对http,https通用

其他比如ftp,socket等设置可以参考官方文档: https://docs.oracle.com/javase/8/docs/technotes/guides/net/proxies.html

使用代理服务器

我刚才有讲过,一般情况只是只是转发请求,我们是用不到代理服务器的,但是刚好我遇到了不一般的情况。
我们的服务部署在Kubernetes中,但是有些请求需要走内网访问内部服务,有些请求需要走外网下载文件。而且不能同时给它设置内网ip和public ip(同时设置,访问其他服务时,其他服务会认为是外网在访问)。

因此解决方案是将我们的服务部署在拥有内网访问的worker中,而将代理服务器部署在具有public ip的worker中,当某些访问需要访问外网的时候,走代理服务器即可。
代理服务器我们选择了squid这个老牌产品。

squid

首先部署squid的service

apiVersion: apps/v1
kind: Deployment
metadata:
  name: squid
spec:
  replicas: 1
  selector:
    matchLabels:
      run: squid
  template:
    metadata:
      labels:
        run: squid
    spec:
      nodeSelector:
        node.vks/internet-access: "true"
      volumes:
        - name: proxy-config
          configMap:
            name: proxy-configmap
      containers:
        - name: squid
          image: sameersbn/squid:3.5.27-2
          imagePullPolicy: IfNotPresent
          # 将squid的配置文件挂载到/etc/squid中
          volumeMounts:
            - name: proxy-config
              mountPath: /etc/squid
              readOnly: true
          ports:
            - containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: proxy-service
spec:
  ports:
    - port: 80
  selector:
    run: squid

而proxy.conf的配置实际是默认的,你可以使用默认的,也可以使用这个我优化了的

http_port 80
# Example rule allowing access from your local networks.
# Adapt to list your (internal) IP networks from where browsing
# should be allowed
acl localnet src 10.0.0.0/8 # RFC1918 possible internal network
acl localnet src 172.16.0.0/12  # RFC1918 possible internal network
acl localnet src 192.168.0.0/16 # RFC1918 possible internal network
acl SSL_ports port 443
acl Safe_ports port 80    # http
acl Safe_ports port 21    # ftp
acl Safe_ports port 443   # https
acl Safe_ports port 70    # gopher
acl Safe_ports port 210   # wais
acl Safe_ports port 1025-65535  # unregistered ports
acl Safe_ports port 280   # http-mgmt
acl Safe_ports port 488   # gss-http
acl Safe_ports port 591   # filemaker
acl Safe_ports port 777   # multiling http
acl CONNECT method CONNECT
http_access deny CONNECT !SSL_ports
http_access allow localhost manager
http_access allow localnet
http_access deny manager
http_access allow all
# disable caching
cache deny all
cache_mem 8 MB
cache_dir null /tmp
# disable unnecessary logs
cache_log / dev/null
# To make it anonymous
forwarded_for off
request_header_access Allow allow all
request_header_access Authorization allow all
request_header_access WWW-Authenticate allow all
request_header_access Proxy-Authorization allow all
request_header_access Proxy-Authenticate allow all
request_header_access Cache-Control allow all
request_header_access Content-Encoding allow all
request_header_access Content-Length allow all
request_header_access Content-Type allow all
request_header_access Date allow all
request_header_access Expires allow all
request_header_access Host allow all
request_header_access If-Modified-Since allow all
request_header_access Last-Modified allow all
request_header_access Location allow all
request_header_access Pragma allow all
request_header_access Accept allow all
request_header_access Accept-Charset allow all
request_header_access Accept-Encoding allow all
request_header_access Accept-Language allow all
request_header_access Content-Language allow all
request_header_access Mime-Version allow all
request_header_access Retry-After allow all
request_header_access Title allow all
request_header_access Connection allow all
request_header_access Proxy-Connection allow all
request_header_access User-Agent allow all
request_header_access Cookie allow all
request_header_access All deny all

需要注意的是node.vks/internet-access: "true",squid部署在了具有公网访问权限的worker中。

如果想要验证proxy是否可用,可以通过curl的方式(自行设定proxy)

设定Java运行参数

apiVersion: apps/v1
kind: Deployment
metadata:
  name: helloworld
spec:
  replicas: 1
  selector:
    matchLabels:
      run: helloworld
  template:
    metadata:
      labels:
        run: helloworld
    spec:
      nodeSelector:
        node.vks/intranet: "true"
      containers:
        - name: helloworld
          image: docker-registry.xxx.com/hello_proxy
          imagePullPolicy: Always
          ports:
            - containerPort: 8080
          command: ["java"]
          args: ["-Dhttp.proxyHost=proxy-service", "-Dhttp.proxyPort=80", "-Dhttps.proxyHost=proxy-service", "-Dhttps.proxyPort=80", "-jar", "target/app.jar"]

这里我们将我们的服务通过node.vks/intranet-ip: "true"部署到了内网中。而hello_proxy的代码其实很简单

@PostConstruct
private void init() {
  try {
      System.out.println("http.ProxyHost=" + System.getProperty("http.proxyHost"));
      System.out.println("http.ProxyPort=" + System.getProperty("http.proxyPort"));
      System.out.println("https.ProxyHost=" + System.getProperty("https.proxyHost"));
      System.out.println("https.ProxyPort=" + System.getProperty("https.proxyPort"));
      hostname = InetAddress.getLocalHost().getHostName();
  } catch (UnknownHostException e) {
      hostname = "unknown host";
  }
}

当然你可以自己写一个从外网下载文件的controller或者请求内网服务的controller来验证。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,692评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,482评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,995评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,223评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,245评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,208评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,091评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,929评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,346评论 1 311
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,570评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,739评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,437评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,037评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,677评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,833评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,760评论 2 369
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,647评论 2 354

推荐阅读更多精彩内容

  • Squid简介: 代理服务器是目前网络中常见的服务器之一,它可以提供文件缓存、复制和地址过滤等服务,充分利用有限的...
    阿栋oxo阅读 762评论 0 1
  • 高并发高流量网站架构 Web2.0的兴起,掀起了互联网新一轮的网络创业大潮。以用户为导向的新网站建设概念,细分了网...
    程序o07阅读 682评论 0 5
  • 深入浅出HTTP协议(WEB开发和面试必备) 1.基础概念篇 a.简介 HTTP是Hyper Text Trans...
    半世韶华忆阑珊阅读 1,221评论 0 7
  • 本文整理自MIN飞翔博客 [1] 1. 概念 协议是指计算机通信网络中两台计算机之间进行通信所必须共同遵守的规定或...
    HoyaWhite阅读 2,671评论 2 20
  • 当祁肆坐在这个白色的教堂里的时候,他其实是有非常多的感触的。 特别是当他看见那个男人的时候。 他穿着白色的西装手臂...
    顾薄慎阅读 1,210评论 0 0