Socket Client 적용
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
package com.eactive.testmaster.client.service;
|
||||
|
||||
|
||||
import com.eactive.testmaster.client.dto.ApiRequestDTO;
|
||||
import com.eactive.testmaster.client.dto.ApiResponse;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public interface ApiClient {
|
||||
|
||||
CompletableFuture<ApiResponse> handleRequest(ApiRequestDTO apiRequest);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.eactive.testmaster.client.service;
|
||||
|
||||
import com.eactive.testmaster.client.dto.ApiRequestDTO;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class ApiClientFactory {
|
||||
|
||||
private final NettyHttpApiClient httpApiClient;
|
||||
private final NettyTcpApiClient tcpApiClient;
|
||||
|
||||
public ApiClientFactory(NettyHttpApiClient httpApiClient, NettyTcpApiClient tcpApiClient) {
|
||||
this.httpApiClient = httpApiClient;
|
||||
this.tcpApiClient = tcpApiClient;
|
||||
}
|
||||
|
||||
public ApiClient getClient(ApiRequestDTO request) {
|
||||
switch (request.getType().toUpperCase()) {
|
||||
case "HTTP":
|
||||
return httpApiClient;
|
||||
case "TCP":
|
||||
return tcpApiClient;
|
||||
default:
|
||||
throw new IllegalArgumentException("Unsupported client type: " + request.getType());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -46,10 +46,9 @@ public class ApiRequestMigrationService {
|
||||
}
|
||||
|
||||
apiRequestRepository.findAll().forEach(apiRequest -> {
|
||||
|
||||
apiRequest.setHeaders(apiRequest.getHeaders().replace("=", "::"));
|
||||
apiRequest.setQueryParams(apiRequest.getQueryParams().replace("=", "::"));
|
||||
|
||||
if(apiRequest.getType() == null){
|
||||
apiRequest.setType("HTTP");
|
||||
}
|
||||
apiRequestRepository.save(apiRequest);
|
||||
});
|
||||
|
||||
|
||||
+23
-21
@@ -30,8 +30,9 @@ import javax.net.ssl.SSLException;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
@Service
|
||||
public class NettyApiClient {
|
||||
private static final Logger logger = LoggerFactory.getLogger(NettyApiClient.class);
|
||||
public class NettyHttpApiClient implements ApiClient {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(NettyHttpApiClient.class);
|
||||
|
||||
@Autowired
|
||||
ServerRepository serverRepository;
|
||||
@@ -43,29 +44,30 @@ public class NettyApiClient {
|
||||
|
||||
CompletableFuture<ApiResponse> responseFuture = new CompletableFuture<>();
|
||||
EventLoopGroup group = new NioEventLoopGroup();
|
||||
|
||||
try {
|
||||
Bootstrap b = new Bootstrap()
|
||||
.group(group)
|
||||
.channel(NioSocketChannel.class)
|
||||
.option(ChannelOption.TCP_NODELAY, true)
|
||||
.handler(new ChannelInitializer<Channel>() {
|
||||
@Override
|
||||
public void initChannel(Channel ch) throws SSLException {
|
||||
if (server.getScheme().equalsIgnoreCase("https")) {
|
||||
final SslContext sslCtx = SslContextBuilder.forClient()
|
||||
.trustManager(InsecureTrustManagerFactory.INSTANCE).build();
|
||||
ch.pipeline().addLast(sslCtx.newHandler(ch.alloc(), host, port));// Add SSL handler
|
||||
}
|
||||
|
||||
ch.pipeline().addLast(new HttpClientCodec());
|
||||
ch.pipeline().addLast(new HttpObjectAggregator(65536));
|
||||
ch.pipeline().addLast(new HttpContentDecompressor());
|
||||
ch.pipeline().addLast(new HttpHandler(responseFuture));
|
||||
.group(group)
|
||||
.channel(NioSocketChannel.class)
|
||||
.option(ChannelOption.TCP_NODELAY, true)
|
||||
.handler(new ChannelInitializer<Channel>() {
|
||||
@Override
|
||||
public void initChannel(Channel ch) throws SSLException {
|
||||
if (server.getScheme().equalsIgnoreCase("https")) {
|
||||
final SslContext sslCtx = SslContextBuilder.forClient()
|
||||
.trustManager(InsecureTrustManagerFactory.INSTANCE).build();
|
||||
ch.pipeline().addLast(sslCtx.newHandler(ch.alloc(), host, port));// Add SSL handler
|
||||
}
|
||||
});
|
||||
|
||||
ch.pipeline().addLast(new HttpClientCodec());
|
||||
ch.pipeline().addLast(new HttpObjectAggregator(65536));
|
||||
ch.pipeline().addLast(new HttpContentDecompressor());
|
||||
ch.pipeline().addLast(new HttpHandler(responseFuture));
|
||||
}
|
||||
});
|
||||
|
||||
Channel ch = b.connect(host, port).sync().channel();
|
||||
ByteBuf content = null;
|
||||
ByteBuf content;
|
||||
if (StringUtils.isNotEmpty(apiRequest.getRequestBody())) {
|
||||
content = Unpooled.copiedBuffer(apiRequest.getRequestBody(), CharsetUtil.UTF_8);
|
||||
} else {
|
||||
@@ -94,7 +96,7 @@ public class NettyApiClient {
|
||||
request.headers().add(customHeaders);
|
||||
}
|
||||
|
||||
apiRequest.setSentBytes(request.toString().length());
|
||||
// apiRequest.setSentBytes(request.toString().length());
|
||||
|
||||
ch.writeAndFlush(request);
|
||||
ch.closeFuture().sync();
|
||||
@@ -0,0 +1,106 @@
|
||||
package com.eactive.testmaster.client.service;
|
||||
|
||||
import com.eactive.testmaster.client.dto.ApiRequestDTO;
|
||||
import com.eactive.testmaster.client.dto.ApiResponse;
|
||||
import com.eactive.testmaster.common.exception.ServerNotFoundException;
|
||||
import com.eactive.testmaster.server.entity.Server;
|
||||
import com.eactive.testmaster.server.entity.ServerRepository;
|
||||
import io.netty.bootstrap.Bootstrap;
|
||||
import io.netty.channel.ChannelFuture;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.channel.SimpleChannelInboundHandler;
|
||||
import io.netty.channel.nio.NioEventLoopGroup;
|
||||
import io.netty.channel.socket.SocketChannel;
|
||||
import io.netty.channel.socket.nio.NioSocketChannel;
|
||||
import io.netty.handler.codec.string.StringDecoder;
|
||||
import io.netty.handler.codec.string.StringEncoder;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class NettyTcpApiClient implements ApiClient {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(NettyTcpApiClient.class);
|
||||
|
||||
private final ServerRepository serverRepository;
|
||||
|
||||
public NettyTcpApiClient(ServerRepository serverRepository) {
|
||||
this.serverRepository = serverRepository;
|
||||
}
|
||||
|
||||
public CompletableFuture<ApiResponse> handleRequest(ApiRequestDTO apiRequest) {
|
||||
Server server = serverRepository.findById(apiRequest.getServer()).orElseThrow(() -> new ServerNotFoundException("Server not found"));
|
||||
String host = server.getHostname();
|
||||
int port = server.getPort();
|
||||
|
||||
CompletableFuture<ApiResponse> responseFuture = new CompletableFuture<>();
|
||||
EventLoopGroup group = new NioEventLoopGroup();
|
||||
try {
|
||||
String response = sendMessage(host, port, group, apiRequest.getRequestBody());
|
||||
ApiResponse apiResponse = new ApiResponse();
|
||||
apiResponse.setBody(response);
|
||||
responseFuture.complete(apiResponse);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
ApiResponse response = new ApiResponse();
|
||||
response.setBody("An error occurred: " + e.getMessage());
|
||||
return CompletableFuture.completedFuture(response);
|
||||
} finally {
|
||||
group.shutdownGracefully();
|
||||
}
|
||||
return responseFuture;
|
||||
}
|
||||
|
||||
public String sendMessage(String host, int port, EventLoopGroup group, final String message) throws InterruptedException {
|
||||
final BlockingQueue<String> answer = new ArrayBlockingQueue<>(1);
|
||||
Bootstrap b = new Bootstrap();
|
||||
b.group(group)
|
||||
.channel(NioSocketChannel.class)
|
||||
.handler(new ChannelInitializer<SocketChannel>() {
|
||||
@Override
|
||||
protected void initChannel(SocketChannel ch) {
|
||||
ch.pipeline().addLast(new StringDecoder(), new StringEncoder(), new SimpleChannelInboundHandler<String>() {
|
||||
@Override
|
||||
protected void channelRead0(ChannelHandlerContext ctx, String msg) {
|
||||
answer.offer(msg);
|
||||
ctx.close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelActive(ChannelHandlerContext ctx) {
|
||||
ctx.writeAndFlush(message);
|
||||
// Send message on activation, consider thread safety
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Connect to the server
|
||||
ChannelFuture f = b.connect(host, port).sync();
|
||||
f.channel().closeFuture().sync();
|
||||
|
||||
// Wait for the response
|
||||
return answer.take(); // This will block until a message is available
|
||||
}
|
||||
|
||||
|
||||
// public static void main(String[] args) {
|
||||
// NettyTcpApiClient client = new NettyTcpApiClient();
|
||||
// try {
|
||||
// String response = client.sendMessage("localhost", 30913, "00340000BASICTST010134567890ABCDEF");
|
||||
// System.out.println("Server replied: " + response);
|
||||
// } catch (InterruptedException e) {
|
||||
// Thread.currentThread().interrupt();
|
||||
// e.printStackTrace();
|
||||
// } finally {
|
||||
// client.shutdown();
|
||||
// }
|
||||
// }
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user