This is an automated email from the ASF dual-hosted git repository.

xiaoyu pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/shenyu-client-dotnet.git


The following commit(s) were added to refs/heads/main by this push:
     new 129d20b  [ISSUE #26] Support register by consul for dotnet client (#27)
129d20b is described below

commit 129d20ba4c69710586b41b833bb2d8c0462fda16
Author: Han Gao <[email protected]>
AuthorDate: Wed Aug 3 15:33:51 2022 +0800

    [ISSUE #26] Support register by consul for dotnet client (#27)
    
    * Support register by consul for dotnet client
    
    * deregister consul when close client
---
 .../Utils/ShenyuCollectionExtensions.cs            |  5 ++
 .../Apache.ShenYu.Client.csproj                    |  1 +
 .../Registers/IShenyuRegister.cs                   |  1 +
 .../Registers/ShenyuAbstractRegister.cs            | 59 +++++++++++++++
 .../Registers/ShenyuConsulRegister.cs              | 87 ++++++++++++++++++++++
 .../Registers/ShenyuHttpRegister.cs                | 10 +--
 .../Registers/ShenyuZookeeperRegister.cs           | 39 ++--------
 client/Apache.ShenYu.Client/Utils/Constants.cs     |  9 ++-
 .../AspNetCoreExample/appsettings.Development.json |  7 +-
 examples/AspNetCoreExample/appsettings.json        | 24 +++++-
 10 files changed, 195 insertions(+), 47 deletions(-)

diff --git 
a/client/Apache.ShenYu.AspNetCore/Utils/ShenyuCollectionExtensions.cs 
b/client/Apache.ShenYu.AspNetCore/Utils/ShenyuCollectionExtensions.cs
index fc47a3b..c6ab9b1 100644
--- a/client/Apache.ShenYu.AspNetCore/Utils/ShenyuCollectionExtensions.cs
+++ b/client/Apache.ShenYu.AspNetCore/Utils/ShenyuCollectionExtensions.cs
@@ -64,6 +64,11 @@ namespace Apache.ShenYu.AspNetCore.Utils
                     services.AddSingleton<IShenyuRegister, 
ShenyuZookeeperRegister>();
                     break;
                 }
+                case Constants.RegisterType.Consul:
+                {
+                    services.AddSingleton<IShenyuRegister, 
ShenyuConsulRegister>();
+                    break;
+                }
                 default:
                     throw new Exception($"not supported type 
{shenyuOptions.Register.RegisterType}");
             }
diff --git a/client/Apache.ShenYu.Client/Apache.ShenYu.Client.csproj 
b/client/Apache.ShenYu.Client/Apache.ShenYu.Client.csproj
index c77b2c8..cba2a98 100644
--- a/client/Apache.ShenYu.Client/Apache.ShenYu.Client.csproj
+++ b/client/Apache.ShenYu.Client/Apache.ShenYu.Client.csproj
@@ -49,5 +49,6 @@
     <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" 
Version="2.2.0" />
     <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
     <PackageReference Include="ZooKeeperNetEx" Version="3.4.12.4" />
+    <PackageReference Include="Consul" Version="1.6.10.7" />
   </ItemGroup>
 </Project>
diff --git a/client/Apache.ShenYu.Client/Registers/IShenyuRegister.cs 
b/client/Apache.ShenYu.Client/Registers/IShenyuRegister.cs
index 361597e..a4adce1 100644
--- a/client/Apache.ShenYu.Client/Registers/IShenyuRegister.cs
+++ b/client/Apache.ShenYu.Client/Registers/IShenyuRegister.cs
@@ -18,6 +18,7 @@
 using System.Threading.Tasks;
 using Apache.ShenYu.Client.Models.DTO;
 using Apache.ShenYu.Client.Options;
+using Apache.ShenYu.Client.Utils;
 
 namespace Apache.ShenYu.Client.Registers
 {
diff --git a/client/Apache.ShenYu.Client/Registers/ShenyuAbstractRegister.cs 
b/client/Apache.ShenYu.Client/Registers/ShenyuAbstractRegister.cs
new file mode 100644
index 0000000..ee5cc8a
--- /dev/null
+++ b/client/Apache.ShenYu.Client/Registers/ShenyuAbstractRegister.cs
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System.Threading.Tasks;
+using Apache.ShenYu.Client.Models.DTO;
+using Apache.ShenYu.Client.Options;
+using Apache.ShenYu.Client.Utils;
+
+namespace Apache.ShenYu.Client.Registers
+{
+    public abstract class ShenyuAbstractRegister : IShenyuRegister
+    {
+        protected string BuildMetadataNodeName(MetaDataRegisterDTO metadata)
+        {
+            string nodeName;
+            string rpcType = metadata.rpcType;
+
+            if (Constants.RegisterRpcType.Http.Equals(rpcType) || 
Constants.RegisterRpcType.SpringCloud.Equals(rpcType))
+            {
+                nodeName = string.Join(Constants.SelectorJoinRule, 
metadata.contextPath,
+                    metadata.ruleName.Replace(Constants.PathSeparator, 
Constants.SelectorJoinRule));
+            }
+            else
+            {
+                nodeName = string.Join(".", metadata.serviceName, 
metadata.methodName);
+            }
+
+            return nodeName.StartsWith(Constants.PathSeparator) ? 
nodeName.Substring(1) : nodeName;
+        }
+
+        protected string BuildContextNodePath(string contextPath, string 
appName)
+        {
+            return string.IsNullOrEmpty(contextPath)
+                ? appName
+                : (contextPath.StartsWith("/")
+                    ? contextPath.Substring(1)
+                    : contextPath);
+        }
+
+        public abstract Task Init(ShenyuOptions shenyuOptions);
+        public abstract Task PersistInterface(MetaDataRegisterDTO metadata);
+        public abstract Task PersistURI(URIRegisterDTO registerDTO);
+        public abstract Task Close();
+    }
+}
diff --git a/client/Apache.ShenYu.Client/Registers/ShenyuConsulRegister.cs 
b/client/Apache.ShenYu.Client/Registers/ShenyuConsulRegister.cs
new file mode 100644
index 0000000..2c89ede
--- /dev/null
+++ b/client/Apache.ShenYu.Client/Registers/ShenyuConsulRegister.cs
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+using System.Threading.Tasks;
+using Apache.ShenYu.Client.Models.DTO;
+using Apache.ShenYu.Client.Options;
+using Consul;
+using Microsoft.Extensions.Logging;
+using Newtonsoft.Json;
+
+namespace Apache.ShenYu.Client.Registers
+{
+    public class ShenyuConsulRegister : ShenyuAbstractRegister
+    {
+        private readonly ILogger<ShenyuConsulRegister> _logger;
+        private ShenyuOptions _shenyuOptions;
+        private ConsulClient _client;
+
+        public ShenyuConsulRegister(ILogger<ShenyuConsulRegister> logger)
+        {
+            _logger = logger;
+        }
+
+        public override Task Init(ShenyuOptions shenyuOptions)
+        {
+            this._shenyuOptions = shenyuOptions;
+            ConsulClientConfiguration config = new ConsulClientConfiguration();
+            config.Address = new Uri(this._shenyuOptions.Register.ServerList);
+            this._client = new ConsulClient(config);
+
+            return Task.CompletedTask;
+        }
+
+        public override async Task PersistInterface(MetaDataRegisterDTO 
metadata)
+        {
+            var metadataStr = JsonConvert.SerializeObject(metadata, 
Formatting.None,
+                new JsonSerializerSettings { NullValueHandling = 
NullValueHandling.Ignore });
+            string contextPath = BuildContextNodePath(metadata.contextPath, 
metadata.appName);
+            string parentPath = 
$"/shenyu/register/metadata/{metadata.rpcType}/{contextPath}";
+            string nodeName = BuildMetadataNodeName(metadata);
+            string nodePath = $"{parentPath}/{nodeName}".Substring(1);
+            var putPair = new KVPair(nodePath) { Value = 
Encoding.UTF8.GetBytes(metadataStr) };
+            await this._client.KV.Put(putPair);
+        }
+
+        public override Task PersistURI(URIRegisterDTO registerDTO)
+        {
+            var uriRegString = JsonConvert.SerializeObject(registerDTO, 
Formatting.None,
+                new JsonSerializerSettings { NullValueHandling = 
NullValueHandling.Ignore });
+            var dic = new Dictionary<string, string> { { "uri", uriRegString } 
};
+            this._client.Agent.ServiceRegister(new AgentServiceRegistration
+            {
+                ID = this._shenyuOptions.Register.Props["Id"],
+                Name = this._shenyuOptions.Register.Props["Name"],
+                Tags = this._shenyuOptions.Register.Props["Tags"].Split(','),
+                Port = Int32.Parse(this._shenyuOptions.Register.Props["Port"]),
+                Address = "localhost",
+                EnableTagOverride = 
Boolean.Parse(this._shenyuOptions.Register.Props["EnableTagOverride"]),
+                Meta = dic,
+            });
+
+            return Task.CompletedTask;
+        }
+
+        public override async Task Close()
+        {
+            await 
this._client.Agent.ServiceDeregister(this._shenyuOptions.Register.Props["Id"]);
+        }
+    }
+}
diff --git a/client/Apache.ShenYu.Client/Registers/ShenyuHttpRegister.cs 
b/client/Apache.ShenYu.Client/Registers/ShenyuHttpRegister.cs
index db8e885..1cdaa63 100644
--- a/client/Apache.ShenYu.Client/Registers/ShenyuHttpRegister.cs
+++ b/client/Apache.ShenYu.Client/Registers/ShenyuHttpRegister.cs
@@ -30,7 +30,7 @@ using Newtonsoft.Json.Linq;
 
 namespace Apache.ShenYu.Client.Registers
 {
-    public class ShenyuHttpRegister : IShenyuRegister
+    public class ShenyuHttpRegister : ShenyuAbstractRegister
     {
         private List<string> ServerList { get; set; }
 
@@ -48,7 +48,7 @@ namespace Apache.ShenYu.Client.Registers
             this._logger = logger;
         }
 
-        public async Task Init(ShenyuOptions shenyuOptions)
+        public override async Task Init(ShenyuOptions shenyuOptions)
         {
             this._shenyuOptions = shenyuOptions;
             
this._shenyuOptions.Register.Props.TryGetValue(Constants.RegisterConstants.UserName,
 out this._userName);
@@ -59,18 +59,18 @@ namespace Apache.ShenYu.Client.Registers
             await this.SetAccessTokens();
         }
 
-        public async Task PersistInterface(MetaDataRegisterDTO metadata)
+        public override async Task PersistInterface(MetaDataRegisterDTO 
metadata)
         {
             await this.DoRegister(metadata, Constants.MetaPath, 
Constants.MetaType);
         }
 
-        public async Task PersistURI(URIRegisterDTO registerDTO)
+        public override async Task PersistURI(URIRegisterDTO registerDTO)
         {
             await this.DoRegister(registerDTO, Constants.UriPath, 
Constants.UriType);
             this._uriRegisterDto = registerDTO;
         }
 
-        public Task Close()
+        public override Task Close()
         {
             throw new NotImplementedException();
         }
diff --git a/client/Apache.ShenYu.Client/Registers/ShenyuZookeeperRegister.cs 
b/client/Apache.ShenYu.Client/Registers/ShenyuZookeeperRegister.cs
index 1539918..3f88e1f 100644
--- a/client/Apache.ShenYu.Client/Registers/ShenyuZookeeperRegister.cs
+++ b/client/Apache.ShenYu.Client/Registers/ShenyuZookeeperRegister.cs
@@ -29,7 +29,7 @@ using org.apache.zookeeper;
 
 namespace Apache.ShenYu.Client.Registers
 {
-    public class ShenyuZookeeperRegister : IShenyuRegister
+    public class ShenyuZookeeperRegister : ShenyuAbstractRegister
     {
         private readonly ILogger<ShenyuZookeeperRegister> _logger;
         private string _serverList;
@@ -43,7 +43,7 @@ namespace Apache.ShenYu.Client.Registers
             _logger = logger;
         }
 
-        public Task Init(ShenyuOptions shenyuOptions)
+        public override Task Init(ShenyuOptions shenyuOptions)
         {
             this._shenyuOptions = shenyuOptions;
             this._serverList = shenyuOptions.Register.ServerList;
@@ -55,7 +55,7 @@ namespace Apache.ShenYu.Client.Registers
             return Task.CompletedTask;
         }
 
-        public async Task PersistInterface(MetaDataRegisterDTO metadata)
+        public override async Task PersistInterface(MetaDataRegisterDTO 
metadata)
         {
             // build metadata path
             string rpcType = metadata.rpcType;
@@ -87,7 +87,7 @@ namespace Apache.ShenYu.Client.Registers
             }
         }
 
-        public async Task PersistURI(URIRegisterDTO registerDTO)
+        public override async Task PersistURI(URIRegisterDTO registerDTO)
         {
             // build uri path
             string contextPath = BuildContextNodePath(registerDTO.contextPath, 
registerDTO.appName);
@@ -111,7 +111,7 @@ namespace Apache.ShenYu.Client.Registers
             }
         }
 
-        public async Task Close()
+        public override async Task Close()
         {
             await this._zkClient.closeAsync();
         }
@@ -136,33 +136,6 @@ namespace Apache.ShenYu.Client.Registers
             return zk;
         }
 
-        private string BuildContextNodePath(string contextPath, string appName)
-        {
-            return string.IsNullOrEmpty(contextPath)
-                ? appName
-                : (contextPath.StartsWith("/")
-                    ? contextPath.Substring(1)
-                    : contextPath);
-        }
-
-        private string BuildMetadataNodeName(MetaDataRegisterDTO metadata)
-        {
-            string nodeName;
-            string rpcType = metadata.rpcType;
-
-            if (Constants.RegisterRpcType.Http.Equals(rpcType) || 
Constants.RegisterRpcType.SpringCloud.Equals(rpcType))
-            {
-                nodeName = string.Join(Constants.SelectorJoinRule, 
metadata.contextPath,
-                    metadata.ruleName.Replace(Constants.PathSeparator, 
Constants.SelectorJoinRule));
-            }
-            else
-            {
-                nodeName = string.Join(".", metadata.serviceName, 
metadata.methodName);
-            }
-
-            return nodeName.StartsWith(Constants.PathSeparator) ? 
nodeName.Substring(1) : nodeName;
-        }
-
         class StatWatcher : Watcher
         {
             private readonly ShenyuZookeeperRegister _register;
@@ -193,4 +166,4 @@ namespace Apache.ShenYu.Client.Registers
             }
         }
     }
-}
\ No newline at end of file
+}
diff --git a/client/Apache.ShenYu.Client/Utils/Constants.cs 
b/client/Apache.ShenYu.Client/Utils/Constants.cs
index 684631a..376f055 100644
--- a/client/Apache.ShenYu.Client/Utils/Constants.cs
+++ b/client/Apache.ShenYu.Client/Utils/Constants.cs
@@ -27,7 +27,7 @@ namespace Apache.ShenYu.Client.Utils
 
         public const string MetaType = "metadata";
         public const string UriType = "uri";
-        
+
         public const string SelectorJoinRule = "-";
         public const string PathSeparator = "/";
         public const string DotSeparator = ".";
@@ -36,19 +36,20 @@ namespace Apache.ShenYu.Client.Utils
         {
             public const string Http = "http";
             public const string Zookeeper = "zookeeper";
+            public const string Consul = "consul";
         }
-        
+
         public class RegisterRpcType
         {
             public const string Http = "http";
             public const string SpringCloud = "springCloud";
         }
-        
+
         public class RegisterConstants
         {
             public const string UserName = "UserName";
             public const string Password = "Password";
-            
+
             public const string SessionTimeout = "SessionTimeout";
             public const string ConnectionTimeout = "SessionTimeout";
         }
diff --git a/examples/AspNetCoreExample/appsettings.Development.json 
b/examples/AspNetCoreExample/appsettings.Development.json
index 091d877..2c5199b 100644
--- a/examples/AspNetCoreExample/appsettings.Development.json
+++ b/examples/AspNetCoreExample/appsettings.Development.json
@@ -8,13 +8,12 @@
   },
   "Shenyu": {
     "Register": {
-//      "ServerList": "http://localhost:9095";,
-      "ServerList": "localhost:2181",
-      "RegisterType": "zookeeper",
+      "ServerList": "http://localhost:9095";,
+      "RegisterType": "http",
       "Props": {
         "UserName": "admin",
         "Password": "123456"
-      },
+      }
     },
     "Client": {
       "AppName": "dotnet-example",
diff --git a/examples/AspNetCoreExample/appsettings.json 
b/examples/AspNetCoreExample/appsettings.json
index 81ff877..0b08c84 100644
--- a/examples/AspNetCoreExample/appsettings.json
+++ b/examples/AspNetCoreExample/appsettings.json
@@ -6,5 +6,27 @@
       "Microsoft.Hosting.Lifetime": "Information"
     }
   },
-  "AllowedHosts": "*"
+  "Shenyu": {
+    "Register": {
+      "ServerList": "",
+      "RegisterType": "http",
+      // consul, zookeeper, http
+      "Props": {
+        "UserName": "admin",
+        "Password": "123456"
+        //        "Name": "shenyuAdmin",
+        //        "Id": "shenyuAdmin",
+        //        "Port": 8500,
+        //        "Tags": "tag1, tag2",
+        //        "PreferAgentAddress": false,
+        //        "EnableTagOverride": false
+      }
+    },
+    "Client": {
+      "AppName": "dotnet-example",
+      "ContextPath": "/dotnet",
+      "IsFull": false,
+      "ClientType": "http"
+    }
+  }
 }

Reply via email to