一、squid简介

  Squid 是 Linux 系统中最常用的一款开源代理服务软件,是一个广泛使用的开源代理服务器和Web缓存加速器。它支持多种协议,可以很好地实现 HTTP 和 FTP,以及 DNS 查询、SSL 等应用的缓存代理。常用于提高网络性能、节省带宽、提供访问控制以及实现内容过滤,功能十分强大。

官方网站为: http://www.squid-cache.org

image

作为应用层的代理服务软件,Squid 主要提供缓存加速、应用层过滤控制的功能。

核心特点
(1)、缓存和加速:Squid可以缓存请求的网页、图片和其他文件,这样当同一个资源再次被请求时,它可以快速从本地缓存提供,而不是每次都从原始服务器下载。
(2)、控制访问:Squid可以用来控制哪些内容可以被用户访问。它支持强大的访问控制列表(ACLs),允许管理员根据源地址、目的地、使用的协议等标准过滤内容。
(3)、提供安全性:Squid可以作为一个透明代理来提高网络安全,可以用来拦截恶意流量和提供 SSL/TLS加密的代理服务。
(4)、减少带宽使用:通过缓存频繁访问的内容,Squid可以显著减少带宽需求,特别是在网络连接有限或昂贵的环境中非常有用。
(5)、提高响应时间:由于从近距离缓存提供内容,Squid能够减少数据的往返时间,从而提高响应速度。
(6)、支持多种协议:Squid支持 HTTP、HTTPS、FTP等多种网络协议。

应用场景
(1)、企业网关:在企业环境中,Squid通常用作网关代理,来管理和监控员工的互联网使用。
(2)、ISP缓存解决方案:互联网服务提供商(ISP)使用 Squid来减少带宽使用,加快用户访问互联网资源的速度。
(3)、内容分发网络:Squid可以用作内容分发网络(CDN)的一部分,来提供地理分布式的缓存服务。
(4)、反向代理和负载均衡:Squid还可以配置为反向代理,用于负载均衡和为后端服务器提供缓存服务。
(5)、安全和匿名浏览:Squid还可用于提高浏览的安全性和匿名性,尤其是当结合 VPN或 Tor使用时。

Squid但是和VPN还是有区别的:

(1)、Squid主要用于缓存和控制 HTTP/HTTPS流量,而 VPN用于保护整个网络连接的安全和隐私。
(2)、Squid在隐私保护方面不如 VPN,因为它不会对所有流量进行加密,也不会隐藏用户的真实 IP地址。
(3)、Squid的配置可能比 VPN复杂,尤其是在进行高级过滤和控制时。

二、CENTOS安装squid 代理服务器

 1、服务端

(1)、安装squid

yum -y install squid

(2)、设置开机自启动

systemctl enable squid.service

(3)、配置squid

vim  /etc/squid/squid.conf

配置如下:

#
# Recommended minimum configuration:
#

# Example rule allowing access from your local networks.
# Adapt to list your (internal) IP networks from where browsing
# should be allowed
acl localnet src 0.0.0.1-0.255.255.255  # RFC 1122 "this" network (LAN)
acl localnet src 10.0.0.0/8             # RFC 1918 local private network (LAN)
acl localnet src 100.64.0.0/10          # RFC 6598 shared address space (CGN)
acl localnet src 169.254.0.0/16         # RFC 3927 link-local (directly plugged) machines
acl localnet src 172.16.0.0/12          # RFC 1918 local private network (LAN)
acl localnet src 192.168.0.0/16         # RFC 1918 local private network (LAN)
acl localnet src fc00::/7               # RFC 4193 local private network range
acl localnet src fe80::/10              # RFC 4291 link-local (directly plugged) machines

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

#
# Recommended minimum Access Permission configuration:
#
# Deny requests to certain unsafe ports
http_access deny !Safe_ports

# Deny CONNECT to other than secure SSL ports
http_access deny CONNECT !SSL_ports

# Only allow cachemgr access from localhost
http_access allow localhost manager
http_access deny manager

# We strongly recommend the following be uncommented to protect innocent
# web applications running on the proxy server who think the only
# one who can access services on "localhost" is a local user
#http_access deny to_localhost

#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#

# Example rule allowing access from your local networks.
# Adapt localnet in the ACL section to list your (internal) IP networks
# from where browsing should be allowed
http_access allow localnet
http_access allow localhost

# And finally deny all other access to this proxy
http_access deny all

# Squid normally listens to port 3128
http_port 3128

# Uncomment and adjust the following to add a disk cache directory.
#cache_dir ufs /var/spool/squid 100 16 256

# Leave coredumps in the first cache dir
coredump_dir /var/spool/squid

#
# Add any of your own refresh_pattern entries above these.
#
refresh_pattern ^ftp:           1440    20%     10080
refresh_pattern ^gopher:        1440    0%      1440
refresh_pattern -i (/cgi-bin/|\?) 0     0%      0
refresh_pattern .               0       20%     4320

修改如下:

#
# Recommended minimum configuration:
#

# Example rule allowing access from your local networks.
# Adapt to list your (internal) IP networks from where browsing
# should be allowed
acl client_61 src IP(保密)  # RFC 1122 "this" network (LAN)

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

#
# Recommended minimum Access Permission configuration:
#
# Deny requests to certain unsafe ports
http_access deny !Safe_ports

# Deny CONNECT to other than secure SSL ports
http_access deny CONNECT !SSL_ports

# Only allow cachemgr access from localhost
http_access allow localhost manager
http_access deny manager

# We strongly recommend the following be uncommented to protect innocent
# web applications running on the proxy server who think the only
# one who can access services on "localhost" is a local user
#http_access deny to_localhost

#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#

# Example rule allowing access from your local networks.
# Adapt localnet in the ACL section to list your (internal) IP networks
# from where browsing should be allowed
http_access allow client_61


# And finally deny all other access to this proxy
http_access deny all

# Squid normally listens to port 3128
http_port 3128

# Uncomment and adjust the following to add a disk cache directory.
#cache_dir ufs /var/spool/squid 100 16 256

# Leave coredumps in the first cache dir
coredump_dir /var/spool/squid

#
# Add any of your own refresh_pattern entries above these.
#
refresh_pattern ^ftp:           1440    20%     10080
refresh_pattern ^gopher:        1440    0%      1440
refresh_pattern -i (/cgi-bin/|\?) 0     0%      0
refresh_pattern .               0       20%     4320

(4)、启动服务

# 启动服务
systemctl start squid
# 查看服务状态        
systemctl status squid
# 结束服务    
systemctl stop squid

(5)、查看日志

cat /var/log/squid/access.log
#或
tail -f /var/log/squid/access.log

(6)、开放防火墙

firewall-cmd --zone=public --add-port=3128/tcp --permanent 
firewall-cmd --reload
firewall-cmd --zone=public --list-ports

(7)、想要测试代理是否设置成功,可以在服务器本地测试

在云服务器上,使用curl命令通过代理访问一个网站。假设代理监听在3128端口,且允许本地访问:

curl -x http://localhost:3128 https://www.baidu.com/

如果返回了网页内容,则说明代理在本地工作正常。

三、项目使用

使用代理前代码:

String result = HttpTool.doPost(url, data);

使用代理后代码:

String result = HttpTool.doPost(url, data, useProxyFlag, proxyIp, proxyPort);

参数配置

@Value("${proxy_port}")
private int proxyPort;
@Value("${proxy_ip}")
private String proxyIp;
@Value("${use_proxy_flag}")
private boolean useProxyFlag;

工具类:

public static String doPost(String httpUrl, String data, boolean proxyFlag, String proxyIp, int proxyPort) {

        HttpURLConnection connection = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        BufferedReader bufferedReader = null;
        String result = null;
        try {
            URL url = new URL(httpUrl);


            if(proxyFlag){
                //  关键:创建代理对象
                Proxy proxy = new Proxy(Proxy.Type.HTTP,
                        new InetSocketAddress(proxyIp, proxyPort));

                //  使用带代理的 openConnection
                connection = (HttpURLConnection) url.openConnection(proxy);
            }else {
                // 通过远程url连接对象打开连接
                connection = (HttpURLConnection) url.openConnection();
            }

            // 设置连接请求方式
            connection.setRequestMethod("POST");
            // 设置连接主机服务器超时时间:15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取主机服务器返回数据超时时间:60000毫秒
            connection.setReadTimeout(60000);
            // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
            connection.setDoOutput(true);
            // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
            connection.setRequestProperty("Content-Type", "application/json");
            // 通过连接对象获取一个输出流
            outputStream = connection.getOutputStream();
            // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
            outputStream.write(data.getBytes());
            // 通过连接对象获取一个输入流,向远程读取
            if (connection.getResponseCode() == 200) {
                inputStream = connection.getInputStream();
                // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                StringBuffer stringBuffer = new StringBuffer();
                String temp = null;
                // 循环遍历一行一行读取数据
                while ((temp = bufferedReader.readLine()) != null) {
                    stringBuffer.append(temp);
                    stringBuffer.append("\r\n");
                }
                result = stringBuffer.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != bufferedReader) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != outputStream) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 断开与远程地址url的连接
            connection.disconnect();
        }
        return result;
    }

 

posted on 2026-01-08 17:51  周文豪  阅读(1)  评论(0)    收藏  举报