.NetCore框架Surging系列(一)介绍
.NetCore框架Surging系列(二)HTTP
.NetCore框架Surging系列(三)HTTP本地路由发现过程
.NetCore框架Surging系列(四)RPC客户端过程
.NetCore框架Surging系列(五)路由注册
.NetCore框架Surging系列(六)路由发现
.NetCore框架Surging系列(七)路由监听
.NetCore框架Surging系列(八)性能评估
.NetCore框架Surging系列(九)性能提升
1、生成证书
Netty使用的是JKS,可以由keytool将pfx证书转为jks,或者keytool生成jks证书;
DotNetty使用的是PFX,用OpenSSL生成,原理和详细说明看上篇OpenSSL 生成pfx,以下节选linux下生成pfx证书脚本:
# 生成私钥
openssl genrsa -aes256 -passout "pass:yangyiquan" -out key.pem 4096
# 生成公钥
openssl req -new -x509 -days 3650 -key key.pem -passin "pass:yangyiquan" -out cert.csr -subj "/C=CN"
# 打包为pfx
openssl pkcs12 -export -in cert.csr -inkey key.pem -out dotnett.linux.pfx
## 输入三次密码:yangyiquan
注:需要将证书拷贝到Surging.Core.DotNetty
工程中,服务端、客户端都要,并且在证书属性中将‘生成操作’改为‘内容’,‘复制到输出目录’改为‘如果较新则复制’
2、添加配置
更改工程Surging.Core.CPlatform
文件SurgingServerOptions.cs,添加是否开启SSL/TLS的配置
public bool IsSsl { get; set; } = false; //是否开启SSL/TLS,默认不开启
文件surgingSettings.json
中
{
"Surging": {
//省略其他配置
"Libuv": true, //DotNetty相关配置,使用Libuv库开启异步调用
"IsSsl": true, //是否开启SSL/TLS,如果不开启可删除此配置
//省略其他配置
3、更改服务端
更改工程Surging.Core.DotNetty
监听类DotNettyServerMessageListener.cs
public class DotNettyServerMessageListener : IMessageListener, IDisposable
{
//新加 代码
private X509Certificate2 tlsCertificate = null;
//省略 其他代码
public async Task StartAsync(EndPoint endPoint)
{
//新加 代码
if (AppConfig.ServerOptions.IsSsl)
{
tlsCertificate = new X509Certificate2(Path.Combine(AppContext.BaseDirectory, "dotnetty.linux.pfx"), "yangyiquan");
}
var bootstrap = new ServerBootstrap();
bootstrap
//省略 其他代码
.ChildHandler(new ActionChannelInitializer<IChannel>(channel =>
{
var pipeline = channel.Pipeline;
//新加 代码
if (tlsCertificate != null)
{
pipeline.AddLast(TlsHandler.Server(tlsCertificate));
}
//省略 其他代码
}
//省略 其他代码
}
}
4、更改客户端
更改工程Surging.Core.DotNetty
文件DotNettyTransportClientFactory.cs
//省略 其他代码
public class DotNettyTransportClientFactory : ITransportClientFactory, IDisposable
{
//省略 其他代码
public DotNettyTransportClientFactory(ITransportMessageCodecFactory codecFactory, IHealthCheckService healthCheckService, ILogger<DotNettyTransportClientFactory> logger, IServiceExecutor serviceExecutor)
{
//省略 其他代码
_bootstrap.Handler(new ActionChannelInitializer<ISocketChannel>(c =>
{
//省略 其他代码
//新加代码
X509Certificate2 cert = null;
string targetHost = null;
if (AppConfig.ServerOptions.IsSsl)
{
cert = new X509Certificate2(Path.Combine(AppContext.BaseDirectory, "dotnetty.linux.pfx"), "yangyiquan");
targetHost = cert.GetNameInfo(X509NameType.DnsName, false);
}
if (cert != null)
{
pipeline.AddLast(new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost)));
}
//省略 其他代码
}
}
//省略 其他代码
}