用Toxiproxy和Java的HttpURLConnection
模拟各种连接问题,以查看产生了什么样的错误:连接超时vs.读取超时vs.连接被拒绝…。
结果:
系统:openjdk 11.0.1 2018-10-16
-
(.setConnectTimeout 1)
=> java.net.SocketTimeoutException:连接超时 -
(.setReadTimeout 1)
=>javax.net.ssl.SSLProtocolException: Read timed out
在HTTPS上javax.net.ssl.SSLProtocolException: Read timed out
,java.net.SocketTimeoutException: Read timed out
在HTTP上java.net.SocketTimeoutException: Read timed out
(或Toxiproxy,延迟或超时为5s) - 在端口上没有监听=> java.net.ConnectException:连接被拒绝
- 未配置上游的Toxiproxy(即,端口已打开,但连接没有问题)=>
javax.net.ssl.SSLHandshakeException: Remote host terminated the handshake
HTTPS上javax.net.ssl.SSLHandshakeException: Remote host terminated the handshake
,java.net.SocketTimeoutException: Read timed out
HTTPjava.net.SocketTimeoutException: Read timed out
- limit_data_downstream => java.io.IOException:过早的EOF
(我还无法模拟(但)是“连接中断/断开”。)
设置
先决条件
要在/etc/hosts
添加:
127.0.0.1 proxied.google.com
毒物替代品设置
开始使用抗氧化剂:
docker pull shopify/toxiproxy
# BEFORE we `run` it: case #3
docker run --rm -p 5555:5555 -p 6666:6666 -p 8474:8474 --name toxiproxy -it shopify/toxiproxy
配置它(我们可以只发布到:8474
但是使用CLI更容易):
$ docker exec -it toxiproxy /bin/sh
/ # cd /go/bin/
# ./toxiproxy-cli create google -l 0.0.0.0:6666 -u www.google.com:443 # BEFORE this is run: case #4
# ./toxiproxy-cli toxic add google -t latency -a latency=5000 # case #2
Added downstream latency toxic 'latency_downstream' on proxy 'google
# ./toxiproxy-cli toxic remove google -n latency_downstream
Removed toxic 'latency_downstream' on proxy 'google'# ./toxiproxy-cli toxic add google -t timeout -a timeout=2000 # case #2
Added downstream timeout toxic 'timeout_downstream' on proxy 'google'
# ./toxiproxy-cli toxic remove google -n timeout_downstream
Removed toxic 'timeout_downstream' on proxy 'google'# ./toxiproxy-cli toxic add google -t limit_data -a bytes=5000 # case #5
Added downstream limit_data toxic 'limit_data_downstream' on proxy 'google'
测试代码
(import '[java.net URL HttpURLConnection])
(->(doto ^HttpURLConnection (.openConnection (URL. "https://proxied.google.com:6666/"));; BEWARE: JVM *must* be started with `-Dsun.net.http.allowRestrictedHeaders=true` to allow setting the Host:(.setRequestProperty "Host" "www.google.com")(.setConnectTimeout 1000)(.setReadTimeout 1000))(.getInputStream)slurp)
巴克特
阅读我的toxiproxy模拟网络超时以了解为什么我们需要打扰/etc/hosts
和Host
标头。
翻译自: https://www.javacodegeeks.com/2018/11/java-simulating-connection-problems.html