分布式Netty集群方案 加代码 SpringBoot 版

8 篇文章 0 订阅 ¥49.90 ¥99.00

目录

单机netty是怎么通信的?

多节点集群netty是怎么通信的呢?

netty集群是怎么搭建的呢?

连接上的 client 的 channelId 怎么存入 redis 中?

在集群模式中 客户端1向客户端2发送信息

演示效果


完整的讲解 netty 集群的搭建部署。从0讲解每一步,比如存入的数据是什么样的?多节点消息是怎么通信的?让没有搭建过的童鞋没有疑惑。例如:“唉,我存入redis中的实际是什么?我有没有写对?”

首先说下单机版 netty 的操作

普通的 springboot netty 项目,都是 springboot 项目启动加载完成后,启动netty 服务。代码如下

@Component
public class StartUpRunner implements ApplicationRunner {

    // 启动 netty 服务的代码
	@Override
	public void run(ApplicationArguments args) throws Exception {
		ServerBootstrap.bind(7177).sync();
	}
}
	// netty pipeline,配置 websocket,访问路径是 socket.io
    @Override
	protected void initChannel(NioSocketChannel ch) throws Exception {
		ChannelPipeline pipeline = ch.pipeline();
		pipeline.addLast(new HttpServerCodec())
				.addLast(new ChunkedWriteHandler())
				.addLast(new HttpObjectAggregator(1024 * 1024))
				.addLast(new WebSocketServerProtocolHandler("/s
  • 9
    点赞
  • 72
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 15
    评论
以下是一个简单的示例代码,实现了Springboot+protobuf+Netty传输文件的功能: 1. 定义protobuf消息格式 ```protobuf syntax = "proto3"; message FileRequest { string fileName = 1; } message FileResponse { int32 fileSize = 1; bytes fileContent = 2; } ``` 2. 编写Netty服务端和客户端 Netty服务端: ```java @Component @ChannelHandler.Sharable public class FileServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FileRequest) { FileRequest request = (FileRequest) msg; String fileName = request.getFileName(); File file = new File(fileName); if (file.exists()) { byte[] fileContent = Files.readAllBytes(file.toPath()); FileResponse response = FileResponse.newBuilder() .setFileSize(fileContent.length) .setFileContent(ByteString.copyFrom(fileContent)) .build(); ctx.writeAndFlush(response); } else { // 文件不存在 ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } } else { super.channelRead(ctx, msg); } } } ``` Netty客户端: ```java @Component public class FileClient { private Bootstrap bootstrap; private EventLoopGroup group; private Channel channel; @PostConstruct public void init() { group = new NioEventLoopGroup(); bootstrap = new Bootstrap() .group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new ProtobufVarint32LengthFieldPrepender()); pipeline.addLast(new ProtobufEncoder()); pipeline.addLast(new ProtobufVarint32FrameDecoder()); pipeline.addLast(new ProtobufDecoder(FileResponse.getDefaultInstance())); pipeline.addLast(new FileClientHandler()); } }); } public void getFile(String fileName, String host, int port) throws InterruptedException { channel = bootstrap.connect(host, port).sync().channel(); FileRequest request = FileRequest.newBuilder() .setFileName(fileName) .build(); channel.writeAndFlush(request).sync(); } public void close() { channel.close(); group.shutdownGracefully(); } } @ChannelHandler.Sharable public class FileClientHandler extends SimpleChannelInboundHandler<FileResponse> { @Override protected void channelRead0(ChannelHandlerContext ctx, FileResponse msg) throws Exception { if (msg.getFileSize() > 0) { byte[] fileContent = msg.getFileContent().toByteArray(); // 将文件保存到本地 FileOutputStream fos = new FileOutputStream("local_file"); fos.write(fileContent); fos.close(); } else { // 文件不存在 System.err.println("File not found."); } } } ``` 3. 在Springboot中使用NettySpringboot中,可以使用@Configuration和@Bean注解来配置和启动Netty服务端和客户端: ```java @Configuration public class NettyConfig { @Autowired private FileServerHandler fileServerHandler; @Value("${netty.server.port}") private int serverPort; @Bean(name = "bossGroup") public EventLoopGroup bossGroup() { return new NioEventLoopGroup(); } @Bean(name = "workerGroup") public EventLoopGroup workerGroup() { return new NioEventLoopGroup(); } @Bean(name = "serverBootstrap") public ServerBootstrap serverBootstrap(@Qualifier("bossGroup") EventLoopGroup bossGroup, @Qualifier("workerGroup") EventLoopGroup workerGroup) { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new ProtobufVarint32FrameDecoder()); pipeline.addLast(new ProtobufDecoder(FileRequest.getDefaultInstance())); pipeline.addLast(fileServerHandler); } }); return bootstrap; } @Bean(initMethod = "bind", destroyMethod = "shutdownGracefully") public ChannelFuture serverChannelFuture(@Qualifier("serverBootstrap") ServerBootstrap serverBootstrap) { return serverBootstrap.bind(serverPort); } @Autowired private FileClient fileClient; @Value("${netty.client.host}") private String clientHost; @Value("${netty.client.port}") private int clientPort; @Bean(initMethod = "init", destroyMethod = "close") public FileClient fileClient() { return new FileClient(); } } ``` 4. 实现文件传输功能 在Springboot中,可以使用@RestController注解定义一个HTTP接口,用于调用Netty客户端获取文件: ```java @RestController public class FileController { @Autowired private FileClient fileClient; @GetMapping("/file/{fileName}") public String getFile(@PathVariable String fileName) { try { fileClient.getFile(fileName, "localhost", 8000); return "File downloaded successfully."; } catch (InterruptedException e) { e.printStackTrace(); return "File download failed."; } } } ``` 这样,当调用http://localhost:8080/file/test.txt时,就可以从Netty服务端下载test.txt文件并保存到本地。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

又逢乱世

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值