要实现的功能
在controller中给netty服务器发送消息
案例组成
1.客户端:客户端的配置,业务处理逻辑,从控制器中给Netty服务器发送消息
2.服务端:服务端的配置和业务处理逻辑
客户端和服务端依赖配置
<!-- netty -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>5.0.0.Alpha1</version>
</dependency>
注:其他依赖根据需要添加
客户端
客户端配置类(读取application.yml中的配置)
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class NettyConfig {
/**
* 主机
*/
@Value("${netty.host}")
private String host;
/**
* 端口号
*/
@Value("${netty.port}")
private int port;
@Bean
public NettyClient nettyClient() {
return new NettyClient(host,port);
}
}
application.yml
server:
port: 8900
netty:
port : 8899
host: 127.0.0.1
客户端配置代码(完成连接netty服务器的功能)
import javax.annotation.PostConstruct;
import org.springframework.stereotype.Component;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
@Component
public class NettyClient {
//主机
private String host;
//端口号
private int port;
private EventLoopGroup group;
private Bootstrap b;
private ChannelFuture cf;
public NettyClient(String host, int port) {
this.host = host;
this.port = port;
}
@PostConstruct //此注解会在类创建时被调用
public void init() throws InterruptedException {
group = new NioEventLoopGroup();
b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.handler(new Channel