您可以通过在 (Pact->MockServer->)Netty 前面放置一个ReverseProxy来实现您的要求。
这是一个完整的例子。为了拥有 ReverseProxy,使用了LittleProxy。如前所述,此示例使用pact-jvm-consumer-junit,并使用HtmlUnit进行 HTTP 调用。
import au.com.dius.pact.consumer.Pact;
import au.com.dius.pact.consumer.PactProviderRule;
import au.com.dius.pact.consumer.PactVerification;
import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
import au.com.dius.pact.model.MockProviderConfig;
import au.com.dius.pact.model.PactFragment;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.WebClient;
import java.io.IOException;
import java.net.InetSocketAddress;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.littleshoot.proxy.ChainedProxyAdapter;
import org.littleshoot.proxy.ChainedProxyManager;
import org.littleshoot.proxy.HttpProxyServer;
import org.littleshoot.proxy.impl.DefaultHttpProxyServer;
public class HelloIT {
private static final String PROVIDER_SERVICE_PATH = "/provider-endpoint";
@Rule
public PactProviderRule pactProviderServiceMock
= new PactProviderRule("provider-service", this);
private final String providerServiceReverseProxyUrl;
private static HttpProxyServer createReverseProxy(final MockProviderConfig mockProviderConfig) {
final String ip = mockProviderConfig.getHostname();
final int port = mockProviderConfig.getPort();
final ChainedProxyManager cpm = (httpRequest, chainedProxies) -> {
final ChainedProxyAdapter chainedProxy = new ChainedProxyAdapter() {
@Override
public InetSocketAddress getChainedProxyAddress() {
return new InetSocketAddress(ip, port);
}
};
chainedProxies.add(chainedProxy);
};
return DefaultHttpProxyServer.bootstrap()
.withChainProxyManager(cpm)
.withPort(0)
.withAllowLocalOnly(false)
.withAllowRequestToOriginServer(true)
.start();
}
{
/*
* Pact-mock for provider-service listens on loopback only. Using reverse proxy for interaction
* between consumer-service and provider-service on external IP.
*/
final HttpProxyServer providerServiceReverseProxy
= HelloIT.createReverseProxy(pactProviderServiceMock.getConfig());
this.providerServiceReverseProxyUrl
= "http://<your-external-IP>:" + providerServiceReverseProxy.getListenAddress().getPort();
}
@Pact(consumer = "consumer-service")
public PactFragment createFragment(final PactDslWithProvider builder) {
return builder
.uponReceiving("Some request")
.path(PROVIDER_SERVICE_PATH)
.method("GET")
.willRespondWith()
.status(200)
.toFragment();
}
@Test
@PactVerification
public void index() throws IOException {
final Page page
= new WebClient().getPage(this.providerServiceReverseProxyUrl + PROVIDER_SERVICE_PATH);
Assert.assertEquals(200, page.getWebResponse().getStatusCode());
}
}