[C#/COMMON] NATS.Client 누겟 설치하기
■ NATS.Client 누겟을 설치하는 방법을 보여준다. 1. Visual Studio를 실행한다. 2. [도구] / [NuGet 패키지 관리자] / [패키지 관리자 콘솔] 메뉴를 실행한다.
■ NATS.Client 누겟을 설치하는 방법을 보여준다. 1. Visual Studio를 실행한다. 2. [도구] / [NuGet 패키지 관리자] / [패키지 관리자 콘솔] 메뉴를 실행한다.
■ NATS 서버 정보를 구하는 방법을 보여준다. ▶ varz.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 |
using System; using System.Collections.Generic; using System.Text; namespace TestProject { /// <summary> /// cluster /// </summary> public class cluster { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 주소 - addr /// <summary> /// 주소 /// </summary> public string addr { get; set; } #endregion #region 클러스터 포트 - cluster_port /// <summary> /// 클러스터 포트 /// </summary> public int cluster_port { get; set; } #endregion #region 인증 타임아웃 - auth_timeout /// <summary> /// 인증 타임아웃 /// </summary> public int auth_timeout { get; set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 문자열 구하기 - ToString(indentCount) /// <summary> /// 문자열 구하기 /// </summary> /// <param name="indentCount">들여쓰기 카운트</param> /// <returns>문자열</returns> public string ToString(int indentCount = 0) { string indentString = " ".GetRepeatString(indentCount); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine($"{indentString}addr : {addr }"); stringBuilder.AppendLine($"{indentString}cluster_port : {cluster_port}"); stringBuilder.AppendLine($"{indentString}auth_timeout : {auth_timeout}"); return stringBuilder.ToString(); } #endregion } /// <summary> /// varz /// </summary> public class varz { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 서버 ID - server_id /// <summary> /// 서버 ID /// </summary> public string server_id { get; set; } #endregion #region 버전 - version /// <summary> /// 버전 /// </summary> public string version { get; set; } #endregion #region 원형 - proto /// <summary> /// 원형 /// </summary> public int proto { get; set; } #endregion #region GO 언어 버전 - go /// <summary> /// GO 언어 버전 /// </summary> public string go { get; set; } #endregion #region 호스트 - host /// <summary> /// 호스트 /// </summary> public string host { get; set; } #endregion #region 인증 요구 여부 - auth_required /// <summary> /// 인증 요구 여부 /// </summary> public bool auth_required { get; set; } #endregion #region 연결 URL 리스트 - connect_urls /// <summary> /// 연결 URL 리스트 /// </summary> public List<string> connect_urls { get; set; } #endregion #region 주소 - addr /// <summary> /// 주소 /// </summary> public string addr { get; set; } #endregion #region 최대 연결 수 - max_connections /// <summary> /// 최대 연결 수 /// </summary> public int max_connections { get; set; } #endregion #region PING 주기 - ping_interval /// <summary> /// PING 주기 /// </summary> public long ping_interval { get; set; } #endregion #region PING 최대 횟수 - ping_max /// <summary> /// PING 최대 횟수 /// </summary> public int ping_max { get; set; } #endregion #region HTTP 호스트 - http_host /// <summary> /// HTTP 호스트 /// </summary> public string http_host { get; set; } #endregion #region HTTP 포트 - http_port /// <summary> /// HTTP 포트 /// </summary> public int http_port { get; set; } #endregion #region HTTPS 포트 - https_port /// <summary> /// HTTPS 포트 /// </summary> public int https_port { get; set; } #endregion #region 인증 타임아웃 - auth_timeout /// <summary> /// 인증 타임아웃 /// </summary> public int auth_timeout { get; set; } #endregion #region 최대 컨트롤 라인 - max_control_line /// <summary> /// 최대 컨트롤 라인 /// </summary> public int max_control_line { get; set; } #endregion #region 클러스터 - cluster /// <summary> /// 클러스터 /// </summary> public cluster cluster { get; set; } #endregion #region TLS 타임아웃 - tls_timeout /// <summary> /// TLS 타임아웃 /// </summary> public double tls_timeout { get; set; } #endregion #region 포트 - port /// <summary> /// 포트 /// </summary> public int port { get; set; } #endregion #region 최대 페이로드 - max_payload /// <summary> /// 최대 페이로드 /// </summary> public int max_payload { get; set; } #endregion #region 시작 시간 - start /// <summary> /// 시작 시간 /// </summary> public DateTime start { get; set; } #endregion #region 현재 시간 - now /// <summary> /// 현재 시간 /// </summary> public DateTime now { get; set; } #endregion #region UP 시간 - uptime /// <summary> /// UP 시간 /// </summary> public string uptime { get; set; } #endregion #region 메모리 - mem /// <summary> /// 메모리 /// </summary> public long mem { get; set; } #endregion #region 코어 수 - cores /// <summary> /// 코어 수 /// </summary> public int cores { get; set; } #endregion #region CPU - cpu /// <summary> /// CPU /// </summary> public double cpu { get; set; } #endregion #region 연결 수 - connections /// <summary> /// 연결 수 /// </summary> public int connections { get; set; } #endregion #region 총 연결 수 - total_connections /// <summary> /// 총 연결 수 /// </summary> public int total_connections { get; set; } #endregion #region 라우팅 수 - routes /// <summary> /// 라우팅 수 /// </summary> public int routes { get; set; } #endregion #region 원격지 수 - remotes /// <summary> /// 원격지 수 /// </summary> public int remotes { get; set; } #endregion #region 입력 메시지 수 - in_msgs /// <summary> /// 입력 메시지 수 /// </summary> public long in_msgs { get; set; } #endregion #region 출력 메시지 수 - out_msgs /// <summary> /// 출력 메시지 수 /// </summary> public long out_msgs { get; set; } #endregion #region 입력 바이트 수 - in_bytes /// <summary> /// 입력 바이트 수 /// </summary> public long in_bytes { get; set; } #endregion #region 출력 바이트 수 - out_bytes /// <summary> /// 출력 바이트 수 /// </summary> public long out_bytes { get; set; } #endregion #region SLOW 소비자 수 - slow_consumers /// <summary> /// SLOW 소비자 수 /// </summary> public int slow_consumers { get; set; } #endregion #region 최대 보류 수 - max_pending /// <summary> /// 최대 보류 수 /// </summary> public long max_pending { get; set; } #endregion #region 쓰기 데드라인 - write_deadline /// <summary> /// 쓰기 데드라인 /// </summary> public long write_deadline { get; set; } #endregion #region 구독 수 - subscriptions /// <summary> /// 구독 수 /// </summary> public int subscriptions { get; set; } #endregion #region HTTP 요청 상태 딕셔너리 - http_req_stats /// <summary> /// HTTP 요청 상태 딕셔너리 /// </summary> public Dictionary<string, long> http_req_stats { get; set; } #endregion #region 구성 로드 시간 - config_load_time /// <summary> /// 구성 로드 시간 /// </summary> public DateTime config_load_time { get; set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 문자열 구하기 - ToString() /// <summary> /// 문자열 구하기 /// </summary> /// <returns>문자열</returns> public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine($"server_id : {server_id }"); stringBuilder.AppendLine($"version : {version }"); stringBuilder.AppendLine($"proto : {proto }"); stringBuilder.AppendLine($"go : {go }"); stringBuilder.AppendLine($"host : {host }"); stringBuilder.AppendLine($"auth_required : {auth_required }"); stringBuilder.AppendLine($"connect_urls"); stringBuilder.AppendLine($"--------------------------------------------------"); if(connect_urls != null && connect_urls.Count > 0) { foreach(string connect_url in connect_urls) { stringBuilder.AppendLine($" {connect_url}"); } } stringBuilder.AppendLine($"--------------------------------------------------"); stringBuilder.AppendLine($"addr : {addr }"); stringBuilder.AppendLine($"max_connections : {max_connections }"); stringBuilder.AppendLine($"ping_interval : {ping_interval }"); stringBuilder.AppendLine($"ping_max : {ping_max }"); stringBuilder.AppendLine($"http_host : {http_host }"); stringBuilder.AppendLine($"http_port : {http_port }"); stringBuilder.AppendLine($"https_port : {https_port }"); stringBuilder.AppendLine($"auth_timeout : {auth_timeout }"); stringBuilder.AppendLine($"max_control_line : {max_control_line }"); stringBuilder.AppendLine($"cluster : {cluster }"); stringBuilder.AppendLine($"--------------------------------------------------"); stringBuilder.AppendLine($"{cluster.ToString(4)}"); stringBuilder.AppendLine($"--------------------------------------------------"); stringBuilder.AppendLine($"tls_timeout : {tls_timeout }"); stringBuilder.AppendLine($"port : {port }"); stringBuilder.AppendLine($"max_payload : {max_payload }"); stringBuilder.AppendLine($"start : {start }"); stringBuilder.AppendLine($"now : {now }"); stringBuilder.AppendLine($"uptime : {uptime }"); stringBuilder.AppendLine($"mem : {mem }"); stringBuilder.AppendLine($"cores : {cores }"); stringBuilder.AppendLine($"cpu : {cpu }"); stringBuilder.AppendLine($"connections : {connections }"); stringBuilder.AppendLine($"total_connections : {total_connections}"); stringBuilder.AppendLine($"routes : {routes }"); stringBuilder.AppendLine($"remotes : {remotes }"); stringBuilder.AppendLine($"in_msgs : {in_msgs }"); stringBuilder.AppendLine($"out_msgs : {out_msgs }"); stringBuilder.AppendLine($"in_bytes : {in_bytes }"); stringBuilder.AppendLine($"out_bytes : {out_bytes }"); stringBuilder.AppendLine($"slow_consumers : {slow_consumers }"); stringBuilder.AppendLine($"max_pending : {max_pending }"); stringBuilder.AppendLine($"write_deadline : {write_deadline }"); stringBuilder.AppendLine($"subscriptions : {subscriptions }"); stringBuilder.AppendLine($"http_req_stats"); stringBuilder.AppendLine($"--------------------------------------------------"); if(http_req_stats != null && http_req_stats.Count > 0) { int maximumKeyLength = 0; foreach(KeyValuePair<string, long> keyValuePair in http_req_stats) { if(keyValuePair.Key.Length > maximumKeyLength) { maximumKeyLength = keyValuePair.Key.Length; } } foreach(KeyValuePair<string, long> keyValuePair in http_req_stats) { string key = $"{keyValuePair.Key}{" ".GetRepeatString(maximumKeyLength - keyValuePair.Key.Length)}"; stringBuilder.AppendLine($" {key} : {keyValuePair.Value}"); } } stringBuilder.AppendLine($"--------------------------------------------------"); stringBuilder.AppendLine($"config_load_time : {config_load_time }"); return stringBuilder.ToString(); } #endregion } } |
▶ connz.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 |
using System; using System.Collections.Generic; using System.Text; namespace TestProject { /// <summary> /// connection /// </summary> public class connection { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 연결 ID - cid /// <summary> /// 연결 ID /// </summary> public long cid { get; set; } #endregion #region IP 주소 - ip /// <summary> /// IP 주소 /// </summary> public string ip { get; set; } #endregion #region 포트 - port /// <summary> /// 포트 /// </summary> public int port { get; set; } #endregion #region 시작 시간 - start /// <summary> /// 시작 시간 /// </summary> public DateTime start { get; set; } #endregion #region 마지막 활동 시간 - last_activity /// <summary> /// 마지막 활동 시간 /// </summary> public DateTime last_activity { get; set; } #endregion #region RTT - rtt /// <summary> /// RTT /// </summary> public string rtt { get; set; } #endregion #region UP 시간 - uptime /// <summary> /// UP 시간 /// </summary> public string uptime { get; set; } #endregion #region 보류 바이트 수 - pending_bytes /// <summary> /// 보류 바이트 수 /// </summary> public long pending_bytes { get; set; } #endregion #region 입력 메시지 수 - in_msgs /// <summary> /// 입력 메시지 수 /// </summary> public long in_msgs { get; set; } #endregion #region 출력 메시지 수 - out_msgs /// <summary> /// 출력 메시지 수 /// </summary> public long out_msgs { get; set; } #endregion #region 입력 바이트 수 - in_bytes /// <summary> /// 입력 바이트 수 /// </summary> public long in_bytes { get; set; } #endregion #region 출력 바이트 수 - out_bytes /// <summary> /// 출력 바이트 수 /// </summary> public long out_bytes { get; set; } #endregion #region 구독 수 - subscriptions /// <summary> /// 구독 수 /// </summary> public long subscriptions { get; set; } #endregion #region 프로그래밍 언어 - lang /// <summary> /// 프로그래밍 언어 /// </summary> public string lang { get; set; } #endregion #region 버전 - version /// <summary> /// 버전 /// </summary> public string version { get; set; } #endregion #region 구독 리스트 - subscriptions_list /// <summary> /// 구독 리스트 /// </summary> public List<string> subscriptions_list { get; set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 문자열 구하기 - ToString(indentCount) /// <summary> /// 문자열 구하기 /// </summary> /// <param name="indentCount">들여쓰기 카운트</param> /// <returns>문자열</returns> public string ToString(int indentCount = 0) { string indentString = " ".GetRepeatString(indentCount); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine($"{indentString}cid : {cid }"); stringBuilder.AppendLine($"{indentString}ip : {ip }"); stringBuilder.AppendLine($"{indentString}port : {port }"); stringBuilder.AppendLine($"{indentString}start : {start }"); stringBuilder.AppendLine($"{indentString}last_activity : {last_activity}"); stringBuilder.AppendLine($"{indentString}rtt : {rtt }"); stringBuilder.AppendLine($"{indentString}uptime : {uptime }"); stringBuilder.AppendLine($"{indentString}pending_bytes : {pending_bytes}"); stringBuilder.AppendLine($"{indentString}in_msgs : {in_msgs }"); stringBuilder.AppendLine($"{indentString}out_msgs : {out_msgs }"); stringBuilder.AppendLine($"{indentString}in_bytes : {in_bytes }"); stringBuilder.AppendLine($"{indentString}out_bytes : {out_bytes }"); stringBuilder.AppendLine($"{indentString}subscriptions : {subscriptions}"); stringBuilder.AppendLine($"{indentString}lang : {lang }"); stringBuilder.AppendLine($"{indentString}version : {version }"); if(subscriptions_list != null && subscriptions_list.Count > 0) { stringBuilder.AppendLine($"{indentString}subscriptions_list"); stringBuilder.AppendLine($"{indentString}--------------------------------------------------"); for(int i = 0; i < subscriptions_list.Count; i++) { stringBuilder.AppendLine($"{indentString} {subscriptions_list[i]}"); } stringBuilder.AppendLine($"{indentString}--------------------------------------------------"); } return stringBuilder.ToString(); } #endregion } /// <summary> /// connz /// </summary> public class connz { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 서버 ID - server_id /// <summary> /// 서버 ID /// </summary> public string server_id { get; set; } #endregion #region 현재 시간 - now /// <summary> /// 현재 시간 /// </summary> public DateTime now { get; set; } #endregion #region 연결 수 - num_connections /// <summary> /// 연결 수 /// </summary> public long num_connections { get; set; } #endregion #region 전체 수 - total /// <summary> /// 전체 수 /// </summary> public long total { get; set; } #endregion #region 오프셋 - offset /// <summary> /// 오프셋 /// </summary> public long offset { get; set; } #endregion #region 제한 - limit /// <summary> /// 제한 /// </summary> public long limit { get; set; } #endregion #region 연결 리스트 - connections /// <summary> /// 연결 리스트 /// </summary> public List<connection> connections { get; set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 문자열 구하기 - ToString() /// <summary> /// 문자열 구하기 /// </summary> /// <returns>문자열</returns> public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine($"server_id : {server_id }"); stringBuilder.AppendLine($"now : {now }"); stringBuilder.AppendLine($"num_connections : {num_connections}"); stringBuilder.AppendLine($"total : {total }"); stringBuilder.AppendLine($"offset : {offset }"); stringBuilder.AppendLine($"limit : {limit }"); if(connections != null && connections.Count > 0) { stringBuilder.AppendLine($"connections"); stringBuilder.AppendLine($"--------------------------------------------------"); for(int i = 0; i < connections.Count; i++) { connection connection = connections[i]; if(i > 0) { stringBuilder.AppendLine(); } stringBuilder.AppendLine(connection.ToString(4)); } stringBuilder.AppendLine($"--------------------------------------------------"); } return stringBuilder.ToString(); } #endregion } } |
▶ routez.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 |
using System; using System.Collections.Generic; using System.Text; namespace TestProject { /// <summary> /// route /// </summary> public class route { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 라우팅 ID - rid /// <summary> /// 라우팅 ID /// </summary> public int rid { get; set; } #endregion #region 원격 ID - remote_id /// <summary> /// 원격 ID /// </summary> public string remote_id { get; set; } #endregion #region DID SOLICIT - did_solicit /// <summary> /// DID SOLICIT /// </summary> public bool did_solicit { get; set; } #endregion #region 구성 여부 - is_configured /// <summary> /// 구성 여부 /// </summary> public bool is_configured { get; set; } #endregion #region IP 주소 - ip /// <summary> /// IP 주소 /// </summary> public string ip { get; set; } #endregion #region 포트 - port /// <summary> /// 포트 /// </summary> public int port { get; set; } #endregion #region 보류 크기 - pending_size /// <summary> /// 보류 크기 /// </summary> public long pending_size { get; set; } #endregion #region 입력 메시지 수 - in_msgs /// <summary> /// 입력 메시지 수 /// </summary> public long in_msgs { get; set; } #endregion #region 출력 메시지 수 - out_msgs /// <summary> /// 출력 메시지 수 /// </summary> public long out_msgs { get; set; } #endregion #region 입력 바이트 수 - in_bytes /// <summary> /// 입력 바이트 수 /// </summary> public long in_bytes { get; set; } #endregion #region 출력 바이트 수 - out_bytes /// <summary> /// 출력 바이트 수 /// </summary> public long out_bytes { get; set; } #endregion #region 구독 수 - subscriptions /// <summary> /// 구독 수 /// </summary> public int subscriptions { get; set; } #endregion #region 구독 리스트 - subscriptions_list /// <summary> /// 구독 리스트 /// </summary> public List<string> subscriptions_list { get; set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 문자열 구하기 - ToString(indentCount) /// <summary> /// 문자열 구하기 /// </summary> /// <param name="indentCount">들여쓰기 카운트</param> /// <returns>문자열</returns> public string ToString(int indentCount = 0) { string indentString = " ".GetRepeatString(indentCount); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine($"{indentString}rid : {rid }"); stringBuilder.AppendLine($"{indentString}remote_id : {remote_id }"); stringBuilder.AppendLine($"{indentString}did_solicit : {did_solicit }"); stringBuilder.AppendLine($"{indentString}is_configured : {is_configured}"); stringBuilder.AppendLine($"{indentString}ip : {ip }"); stringBuilder.AppendLine($"{indentString}port : {port }"); stringBuilder.AppendLine($"{indentString}pending_size : {pending_size }"); stringBuilder.AppendLine($"{indentString}in_msgs : {in_msgs }"); stringBuilder.AppendLine($"{indentString}out_msgs : {out_msgs }"); stringBuilder.AppendLine($"{indentString}in_bytes : {in_bytes }"); stringBuilder.AppendLine($"{indentString}out_bytes : {out_bytes }"); stringBuilder.AppendLine($"{indentString}subscriptions : {subscriptions}"); stringBuilder.AppendLine($"{indentString}subscriptions_list"); stringBuilder.AppendLine($"{indentString}--------------------------------------------------"); if(subscriptions_list != null && subscriptions_list.Count > 0) { foreach(string subscription in subscriptions_list) { stringBuilder.AppendLine($"{indentString} {subscription}"); } } stringBuilder.AppendLine($"{indentString}--------------------------------------------------"); return stringBuilder.ToString(); } #endregion } /// <summary> /// routez /// </summary> public class routez { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 서버 ID - server_id /// <summary> /// 서버 ID /// </summary> public string server_id { get; set; } #endregion #region 현재 시간 - now /// <summary> /// 현재 시간 /// </summary> public DateTime now { get; set; } #endregion #region 라우팅 리스트 - routes /// <summary> /// 라우팅 리스트 /// </summary> public List<route> routes { get; set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 문자열 구하기 - ToString() /// <summary> /// 문자열 구하기 /// </summary> /// <returns>문자열</returns> public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine($"server_id : {server_id }"); stringBuilder.AppendLine($"now : {now }"); stringBuilder.AppendLine($"routes"); stringBuilder.AppendLine($"--------------------------------------------------"); if(routes != null && routes.Count > 0) { foreach(route route in routes) { stringBuilder.AppendLine(route.ToString(4)); } } stringBuilder.AppendLine($"--------------------------------------------------"); return stringBuilder.ToString(); } #endregion } } |
▶ subsz.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 |
using System.Collections.Generic; using System.Text; namespace TestProject { /// <summary> /// subscription /// </summary> public class subscription { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 서브젝트 - subject /// <summary> /// 서브젝트 /// </summary> public string subject { get; set; } #endregion #region 서브젝트 ID - sid /// <summary> /// 서브젝트 ID /// </summary> public int sid { get; set; } #endregion #region 메시지 수 - msgs /// <summary> /// 메시지 수 /// </summary> public long msgs { get; set; } #endregion #region 클러스터 ID - cid /// <summary> /// 클러스터 ID /// </summary> public int cid { get; set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 문자열 구하기 - ToString(indentCount) /// <summary> /// 문자열 구하기 /// </summary> /// <param name="indentCount">들여쓰기 카운트</param> /// <returns>문자열</returns> public string ToString(int indentCount = 0) { string indentString = " ".GetRepeatString(indentCount); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine($"{indentString}subject : {subject}"); stringBuilder.AppendLine($"{indentString}sid : {sid }"); stringBuilder.AppendLine($"{indentString}msgs : {msgs }"); stringBuilder.AppendLine($"{indentString}cid : {cid }"); return stringBuilder.ToString(); } #endregion } /// <summary> /// subsz /// </summary> public class subsz { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 구독 수 - num_subscriptions /// <summary> /// 구독 수 /// </summary> public long num_subscriptions { get; set; } #endregion #region 캐시 수 - num_cache /// <summary> /// 캐시 수 /// </summary> public long num_cache { get; set; } #endregion #region 삽입 수 - num_inserts /// <summary> /// 삽입 수 /// </summary> public long num_inserts { get; set; } #endregion #region 제거 수 - num_removes /// <summary> /// 제거 수 /// </summary> public long num_removes { get; set; } #endregion #region 매칭 수 - num_matches /// <summary> /// 매칭 수 /// </summary> public long num_matches { get; set; } #endregion #region 캐시 히트 비율 - cache_hit_rate /// <summary> /// 캐시 히트 비율 /// </summary> public double cache_hit_rate { get; set; } #endregion #region 최대 FANOUT - max_fanout /// <summary> /// 최대 FANOUT /// </summary> public double max_fanout { get; set; } #endregion #region 평균 FANOUT - avg_fanout /// <summary> /// 평균 FANOUT /// </summary> public double avg_fanout { get; set; } #endregion #region 전체 수 - total /// <summary> /// 전체 수 /// </summary> public long total { get; set; } #endregion #region 오프셋 - offset /// <summary> /// 오프셋 /// </summary> public long offset { get; set; } #endregion #region 제한 수 - limit /// <summary> /// 제한 수 /// </summary> public long limit { get; set; } #endregion #region 구독 리스트 - subscriptions_list /// <summary> /// 구독 리스트 /// </summary> public List<subscription> subscriptions_list { get; set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 문자열 구하기 - ToString() /// <summary> /// 문자열 구하기 /// </summary> /// <returns>문자열</returns> public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine($"num_subscriptions : {num_subscriptions}"); stringBuilder.AppendLine($"num_cache : {num_cache }"); stringBuilder.AppendLine($"num_inserts : {num_inserts }"); stringBuilder.AppendLine($"num_removes : {num_removes }"); stringBuilder.AppendLine($"num_matches : {num_matches }"); stringBuilder.AppendLine($"cache_hit_rate : {cache_hit_rate }"); stringBuilder.AppendLine($"max_fanout : {max_fanout }"); stringBuilder.AppendLine($"avg_fanout : {avg_fanout }"); stringBuilder.AppendLine($"total : {total }"); stringBuilder.AppendLine($"offset : {offset }"); stringBuilder.AppendLine($"limit : {limit }"); if(subscriptions_list != null && subscriptions_list.Count > 0) { stringBuilder.AppendLine($"subscriptions_list"); stringBuilder.AppendLine($"--------------------------------------------------"); for(int i = 0; i < subscriptions_list.Count; i++) { subscription subscription = subscriptions_list[i]; if(i > 0) { stringBuilder.AppendLine(); } stringBuilder.AppendLine(subscription.ToString(4)); } stringBuilder.AppendLine($"--------------------------------------------------"); } return stringBuilder.ToString(); } #endregion } } |
▶ NATSHelper.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 |
using System.Collections.Generic; using System.Text; using Newtonsoft.Json; namespace TestProject { /// <summary> /// NATS 헬퍼 /// </summary> public static class NATSHelper { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 서버 정보 구하기 - GetVARZ(serverAddress, serverPort) /// <summary> /// 서버 정보 구하기 /// </summary> /// <param name="serverAddress">서버 주소</param> /// <param name="serverPort">서버 포트</param> /// <returns>서버 정보</returns> public static varz GetVARZ(string serverAddress, int serverPort) { string url = $"http://{serverAddress}:{serverPort}/varz"; string contentType = "application/json; charset=utf8"; Encoding encoding = Encoding.UTF8; string argument = string.Empty; string json = HTTPHelper.GetStringPOSTRequest(url, contentType, encoding, argument); varz varz = JsonConvert.DeserializeObject<varz>(json); return varz; } #endregion #region 연결 정보 구하기 - GetCONNZ(serverAddress, serverPort, limit, offset, includeSubscriptionList) /// <summary> /// 연결 정보 구하기 /// </summary> /// <param name="serverAddress">서버 주소</param> /// <param name="serverPort">서버 포트</param> /// <param name="itemLimitCount">항목 제한 수</param> /// <param name="itemOffset">항목 오프셋</param> /// <param name="includeSubscriptionList">구독 리스트 포함 여부</param> /// <returns>연결 정보</returns> public static connz GetCONNZ(string serverAddress, int serverPort, int itemLimitCount, int itemOffset, bool includeSubscriptionList = true) { string url = $"http://{serverAddress}:{serverPort}/connz?limit={itemLimitCount}&offset={itemOffset}" + (includeSubscriptionList ? "&subs=1" : string.Empty); string contentType = "application/json; charset=utf8"; Encoding encoding = Encoding.UTF8; string argument = string.Empty; string json = HTTPHelper.GetStringPOSTRequest(url, contentType, encoding, argument); connz connz = JsonConvert.DeserializeObject<connz>(json); return connz; } #endregion #region 연결 정보 구하기 - GetCONNZ(serverAddress, serverPort) /// <summary> /// 연결 정보 구하기 /// </summary> /// <param name="serverAddress">서버 주소</param> /// <param name="serverPort">서버 포트</param> /// <returns>연결 정보</returns> public static connz GetCONNZ(string serverAddress, int serverPort) { int limit = 1024; int current = 0; connz resultCONNZ = new connz(); resultCONNZ.connections = new List<connection>(); while(true) { connz connz = NATSHelper.GetCONNZ(serverAddress, serverPort, limit, current, true); resultCONNZ.server_id = connz.server_id; resultCONNZ.now = connz.now; resultCONNZ.num_connections += connz.num_connections; resultCONNZ.total = connz.total; resultCONNZ.offset = connz.offset; resultCONNZ.limit = connz.limit; foreach(connection connection in connz.connections) { resultCONNZ.connections.Add(connection); } current += limit; if(current >= connz.total) { break; } } return resultCONNZ; } #endregion #region 라우팅 정보 구하기 - GetROUTEZ(serverAddress, serverPort, includeSubscriptionList) /// <summary> /// 라우팅 정보 구하기 /// </summary> /// <param name="serverAddress">서버 주소</param> /// <param name="serverPort">서버 포트</param> /// <param name="includeSubscriptionList">구독 리스트 포함 여부</param> /// <returns>라우팅 정보</returns> public static routez GetROUTEZ(string serverAddress, int serverPort, bool includeSubscriptionList = true) { string url = $"http://{serverAddress}:{serverPort}/routez" + (includeSubscriptionList ? "?subs=1" : string.Empty); string contentType = "application/json; charset=utf8"; Encoding encoding = Encoding.UTF8; string argument = string.Empty; string json = HTTPHelper.GetStringPOSTRequest(url, contentType, encoding, argument); routez routez = JsonConvert.DeserializeObject<routez>(json); return routez; } #endregion #region 구독 정보 구하기 - GetSUBSZ(serverAddress, serverPort, limit, offset, includeSubscriptionList) /// <summary> /// 구독 정보 구하기 /// </summary> /// <param name="serverAddress">서버 주소</param> /// <param name="serverPort">서버 포트</param> /// <param name="itemLimitCount">항목 제한 수</param> /// <param name="itemOffset">항목 오프셋</param> /// <param name="includeSubscriptionList">구독 리스트 포함 여부</param> /// <returns>구독 정보</returns> public static subsz GetSUBSZ(string serverAddress, int serverPort, int itemLimitCount, int itemOffset, bool includeSubscriptionList = true) { string url = $"http://{serverAddress}:{serverPort}/subsz?limit={itemLimitCount}&offset={itemOffset}" + (includeSubscriptionList ? "&subs=1" : string.Empty); string contentType = "application/json; charset=utf8"; Encoding encoding = Encoding.UTF8; string argument = string.Empty; string json = HTTPHelper.GetStringPOSTRequest(url, contentType, encoding, argument); subsz subsz = JsonConvert.DeserializeObject<subsz>(json); return subsz; } #endregion #region 구독 정보 구하기 - GetSUBSZ(serverAddress, serverPort) /// <summary> /// 구독 정보 구하기 /// </summary> /// <param name="serverAddress">서버 주소</param> /// <param name="serverPort">서버 포트</param> /// <returns>구독 정보</returns> public static subsz GetSUBSZ(string serverAddress, int serverPort) { int limit = 1024; int current = 0; subsz resultSUBSZ = new subsz(); resultSUBSZ.subscriptions_list = new List<subscription>(); while(true) { subsz subsz = NATSHelper.GetSUBSZ("127.0.0.1", 20030, limit, current); resultSUBSZ.num_subscriptions = subsz.num_subscriptions; resultSUBSZ.num_cache = subsz.num_cache; resultSUBSZ.num_inserts = subsz.num_inserts; resultSUBSZ.num_removes = subsz.num_removes; resultSUBSZ.num_matches = subsz.num_matches; resultSUBSZ.cache_hit_rate = subsz.cache_hit_rate; resultSUBSZ.max_fanout = subsz.max_fanout; resultSUBSZ.avg_fanout = subsz.avg_fanout; resultSUBSZ.total += subsz.total; resultSUBSZ.offset = subsz.offset; resultSUBSZ.limit = subsz.limit; foreach(subscription subscription in subsz.subscriptions_list) { resultSUBSZ.subscriptions_list.Add(subscription); } if(subsz.total < limit) { break; } current += limit; } return resultSUBSZ; } #endregion } } |
■ 클러스터 서버용 NATS 클라이언트를 사용하는 방법을 보여준다. [TestCommon 프로젝트] ▶ ServerInfo.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 |
using System; using NATS.Client; namespace TestCommon { /// <summary> /// 서버 정보 /// </summary> public class ServerInfo : IDisposable { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// NATS 옵션 /// </summary> private Options options; /// <summary> /// NATS 연결 /// </summary> private IConnection connection = null; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region NATS 옵션 - Options /// <summary> /// NATS 옵션 /// </summary> public Options Options { get { return this.options; } } #endregion #region NATS 연결 - Connection /// <summary> /// NATS 연결 /// </summary> public IConnection Connection { get { return this.connection; } } #endregion #region 서버 URL - URL /// <summary> /// 서버 URL /// </summary> public string URL { get { return this.options.Url; } } #endregion #region 사용자 ID - User /// <summary> /// 사용자 ID /// </summary> public string User { get { return this.options.User; } } #endregion #region 서버 URL 배열 - Servers /// <summary> /// 서버 URL 배열 /// </summary> public string[] Servers { get { return this.options.Servers; } } #endregion #region PING 주기 - PingInterval /// <summary> /// PING 주기 /// </summary> public int PingInterval { get { return this.options.PingInterval; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - ServerInfo(options) /// <summary> /// 생성자 /// </summary> /// <param name="options">NATS 옵션</param> public ServerInfo(Options options) { this.options = options; } #endregion #region 생성자 - ServerInfo(url, user, password, servers, pingInterval) /// <summary> /// 생성자 /// </summary> /// <param name="url">URL</param> /// <param name="user">사용자 ID</param> /// <param name="password">패스워드</param> /// <param name="servers">서버 주소 배열</param> /// <param name="pingInterval">PING 주기</param> public ServerInfo(string url, string user, string password, string[] servers = null, int pingInterval = 2000) { Options options = ConnectionFactory.GetDefaultOptions(); options.Url = url; options.User = user; options.Password = password; options.Servers = servers; options.PingInterval = pingInterval; this.options = options; } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 생성자 - ServerInfo() /// <summary> /// 생성자 /// </summary> private ServerInfo() { } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 서버 연결하기 - ConnectServer() /// <summary> /// 서버 연결하기 /// </summary> public void ConnectServer() { this.connection = new ConnectionFactory().CreateConnection(this.options); } #endregion #region 서버 연결 끊기 - DisconnectServer() /// <summary> /// 서버 연결 끊기 /// </summary> public void DisconnectServer() { if(this.connection != null) { try { this.connection.Dispose(); } catch { } finally { this.connection = null; } } } #endregion #region 리소스 해제하기 - Dispose() /// <summary> /// 리소스 해제하기 /// </summary> public void Dispose() { DisconnectServer(); } #endregion } } |
▶ SubscriptionInfo.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 |
using System; using NATS.Client; namespace TestCommon { /// <summary> /// 구독 정보 /// </summary> public class SubscriptionInfo : IDisposable { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 서브젝트 /// </summary> private string subject; /// <summary> /// 큐 /// </summary> private string queue; /// <summary> /// 키 /// </summary> private string key; /// <summary> /// 구독 /// </summary> private IAsyncSubscription subscription; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 서브젝트 - Subject /// <summary> /// 서브젝트 /// </summary> public string Subject { get { return this.subject; } } #endregion #region 큐 - Queue /// <summary> /// 큐 /// </summary> public string Queue { get { return this.queue; } } #endregion #region 키 - Key /// <summary> /// 키 /// </summary> public string Key { get { return this.key; } } #endregion #region 구독 - Subscription /// <summary> /// 구독 /// </summary> public IAsyncSubscription Subscription { get { return this.subscription; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - SubscriptionInfo(subject, queue) /// <summary> /// 생성자 /// </summary> /// <param name="subject">서브젝트</param> /// <param name="queue">큐</param> public SubscriptionInfo(string subject, string queue) { if(string.IsNullOrWhiteSpace(subject)) { throw new ArgumentException("subject가 null이거나 공백 문자열 입니다."); } this.subject = subject.Trim(); this.queue = string.IsNullOrWhiteSpace(queue) ? null : queue.Trim(); this.key = GetKey(this.subject, this.queue); this.subscription = null; } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 생성자 - SubscriptionInfo() /// <summary> /// 생성자 /// </summary> private SubscriptionInfo() { } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 키 구하기 - GetKey(subject, queue) /// <summary> /// 키 구하기 /// </summary> /// <param name="subject">서브젝트</param> /// <param name="queue">큐</param> /// <returns>키</returns> public static string GetKey(string subject, string queue) { if(string.IsNullOrWhiteSpace(subject)) { throw new ArgumentException("subject가 null이거나 공백 문자열 입니다."); } string targetSubject = subject.Trim(); string targetQueue = string.IsNullOrWhiteSpace(queue) ? null : queue.Trim(); if(targetQueue == null) { return targetSubject; } else { return $"{targetSubject}_{targetQueue}"; } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Public #region 구독하기 - Subscribe(connection, receivedEventHandler) /// <summary> /// 구독하기 /// </summary> /// <param name="connection">NATS 연결</param> /// <param name="receivedEventHandler">수신 이벤트 핸들러</param> public void Subscribe(IConnection connection, EventHandler<MsgHandlerEventArgs> receivedEventHandler) { this.subscription = connection.SubscribeAsync(this.subject, this.queue, receivedEventHandler); } #endregion #region 구독 취소하기 - Unsubscribe() /// <summary> /// 구독 취소하기 /// </summary> public void Unsubscribe() { if(this.subscription != null) { try { if(this.subscription.IsValid) { try { this.subscription.Unsubscribe(); this.subscription.Dispose(); } catch { } } } finally { this.subscription = null; } } } #endregion #region 리소스 해제하기 - Dispose() /// <summary> /// 리소스 해제하기 /// </summary> public void Dispose() { Unsubscribe(); } #endregion } } |
▶ ReceivedEventArgs.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 |
using System; using NATS.Client; namespace TestCommon { /// <summary> /// 수신시 이벤트 인자 /// </summary> public class ReceivedEventArgs { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 소스 이벤트 인자 /// </summary> private MsgHandlerEventArgs source; /// <summary> /// 응답 데이터 /// </summary> private byte[] replyData; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 서브젝트 - Subject /// <summary> /// 서브젝트 /// </summary> public string Subject { get { return this.source.Message.Subject; } } #endregion #region 데이터 - Data /// <summary> /// 데이터 /// </summary> public byte[] Data { get { return this.source.Message.Data; } } #endregion #region 수신 구독 - ArrivalSubcription /// <summary> /// 수신 구독 /// </summary> public ISubscription ArrivalSubcription { get { return this.source.Message.ArrivalSubcription; } } #endregion #region 응답 서브젝트 - Reply /// <summary> /// 응답 서브젝트 /// </summary> public string Reply { get { return this.source.Message.Reply; } } #endregion #region 응답 데이터 - ReplyData /// <summary> /// 응답 데이터 /// </summary> public byte[] ReplyData { get { return this.replyData; } set { this.replyData = value; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - ReceivedEventArgs(source) /// <summary> /// 생성자 /// </summary> /// <param name="source">소스 이벤트 인자</param> public ReceivedEventArgs(MsgHandlerEventArgs source) { if(source == null) { throw new ArgumentNullException("source가 null 입니다."); } this.source = source; this.replyData = null; } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 생성자 - ReceivedEventArgs() /// <summary> /// 생성자 /// </summary> private ReceivedEventArgs() { } #endregion } } |
▶ NATSClient.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 |
using System; using System.Collections.Generic; using System.Text; using NATS.Client; namespace TestCommon { /// <summary> /// NATS 클라이언트 /// </summary> public class NATSClient : IDisposable { //////////////////////////////////////////////////////////////////////////////////////////////////// Event ////////////////////////////////////////////////////////////////////////////////////////// Public #region 서버 발견시 - ServerDiscovered /// <summary> /// 서버 발견시 /// </summary> public event EventHandler<ConnEventArgs> ServerDiscovered; #endregion #region 재연결시 - Reconnected /// <summary> /// 재연결시 /// </summary> public event EventHandler<ConnEventArgs> Reconnected; #endregion #region 연결 중단시 - Disconnected /// <summary> /// 연결 중단시 /// </summary> public event EventHandler<ConnEventArgs> Disconnected; #endregion #region 폐쇄시 - Closed /// <summary> /// 폐쇄시 /// </summary> public event EventHandler<ConnEventArgs> Closed; #endregion #region 에러시 - Error /// <summary> /// 에러시 /// </summary> public event EventHandler<ErrEventArgs> Error; #endregion #region 수신시 - MessageReceived /// <summary> /// 수신시 /// </summary> public event EventHandler<ReceivedEventArgs> Received; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 서버 정보 /// </summary> private ServerInfo serverInfo = null; /// <summary> /// 구독 정보 딕셔너리 /// </summary> private Dictionary<string, SubscriptionInfo> subscriptionInfoDictionary = null; /// <summary> /// 실행 여부 /// </summary> private bool inRunning = false; /// <summary> /// 동기 객체 /// </summary> private object syncObject; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 서버 정보 - ServerInfo /// <summary> /// 서버 정보 /// </summary> public ServerInfo ServerInfo { get { return this.serverInfo; } } #endregion #region 실행 여부 - IsRunning /// <summary> /// 실행 여부 /// </summary> public bool IsRunning { get { return this.inRunning; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - NATSClient(serverInfo, subscriptionInfoList) /// <summary> /// 생성자 /// </summary> /// <param name="serverInfo">서버 정보</param> /// <param name="subscriptionInfoList">구독 정보 리스트</param> public NATSClient(ServerInfo serverInfo, IList<SubscriptionInfo> subscriptionInfoList) { if(serverInfo == null) { throw new ArgumentNullException("serverInfo가 null 입니다."); } this.serverInfo = serverInfo; #region 구독 정보 딕셔너리를 설정한다. this.subscriptionInfoDictionary = new Dictionary<string, SubscriptionInfo>(); if(subscriptionInfoList != null) { foreach(SubscriptionInfo info in subscriptionInfoList) { if(!this.subscriptionInfoDictionary.ContainsKey(info.Key)) { this.subscriptionInfoDictionary.Add(info.Key, info); } } } #endregion this.syncObject = new object(); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 시작하기 - Start() /// <summary> /// 시작하기 /// </summary> public void Start() { lock(this.syncObject) { if(this.inRunning) { return; } this.inRunning = true; try { Options options = this.serverInfo.Options; options.ServerDiscoveredEventHandler = (sender, e) => { FireServerDiscoveredEvent(e); }; options.ReconnectedEventHandler = (sender, e) => { FireReconnectedEvent(e); }; options.DisconnectedEventHandler = (sender, e) => { FireDisconnectedEvent(e); }; options.ClosedEventHandler = (sender, e) => { FireClosedEvent(e); }; options.AsyncErrorEventHandler = (sender, e) => { FireErrorEvent(e); }; this.serverInfo.ConnectServer(); foreach(KeyValuePair<string, SubscriptionInfo> keyValuePair in this.subscriptionInfoDictionary) { SubscriptionInfo info = keyValuePair.Value; info.Subscribe(this.serverInfo.Connection, (sender, e) => { FireReceivedEvent(e); }); } } catch(Exception exception) { this.inRunning = false; throw exception; } } } #endregion #region 중단하기 - Stop() /// <summary> /// 중단하기 /// </summary> public void Stop() { lock(this.syncObject) { if(!this.inRunning) { return; } this.inRunning = false; foreach(KeyValuePair<string, SubscriptionInfo> keyValuePair in this.subscriptionInfoDictionary) { SubscriptionInfo info = keyValuePair.Value; if(info != null) { info.Unsubscribe(); } } this.serverInfo.DisconnectServer(); Options options = this.serverInfo.Options; options.ServerDiscoveredEventHandler = null; options.ReconnectedEventHandler = null; options.DisconnectedEventHandler = null; options.ClosedEventHandler = null; options.AsyncErrorEventHandler = null; } } #endregion #region 메시지 송신하기 - SendMessage(subject, data) /// <summary> /// 메시지 송신하기 /// </summary> /// <param name="subject">수신 서브젝트</param> /// <param name="data">데이터</param> public void SendMessage(string subject, byte[] data) { if(this.serverInfo.Connection.State == ConnState.CLOSED || this.serverInfo.Connection.State == ConnState.DISCONNECTED) { throw new InvalidOperationException("메시지를 송신할 수 없습니다 : " + this.serverInfo.Connection.State.ToString()); } lock(this.syncObject) { if(string.IsNullOrWhiteSpace(subject)) { throw new ArgumentException("subject가 null이거나 공백 문자열 입니다."); } if(data == null || data.Length == 0) { throw new ArgumentException("data null이거나 길이가 0 입니다."); } int tryCount = 0; do { try { this.serverInfo.Connection.Publish(subject, data); this.serverInfo.Connection.Flush(); return; } catch(Exception exception) { if(tryCount >= 3) { throw exception; } } tryCount++; } while(true); } } #endregion #region 메시지 송신하기 - SendMessage(subject, message) /// <summary> /// 메시지 송신하기 /// </summary> /// <param name="subject">수신 서브젝트</param> /// <param name="message">송신 메시지</param> public void SendMessage(string subject, string message) { byte[] data = Encoding.UTF8.GetBytes(message); SendMessage(subject, data); } #endregion #region 메시지 요청하기 - RequestMessage(subject, data, timeout) /// <summary> /// 메시지 요청하기 /// </summary> /// <param name="subject">수신 서브젝트</param> /// <param name="data">송신 데이터</param> /// <param name="timeout">타임아웃 (디폴트 : 3초)</param> /// <returns>응답 데이터</returns> public byte[] RequestMessage(string subject, byte[] data, int timeout = 3000) { if(this.serverInfo.Connection.State == ConnState.CLOSED || this.serverInfo.Connection.State == ConnState.DISCONNECTED) { throw new InvalidOperationException("메시지를 요청할 수 없습니다 : " + this.serverInfo.Connection.State.ToString()); } lock(this.syncObject) { if(string.IsNullOrWhiteSpace(subject)) { throw new ArgumentException("subject가 null이거나 공백 문자열 입니다."); } if(data == null || data.Length == 0) { throw new ArgumentException("data가 null이거나 길이가 0 입니다."); } int tryCount = 0; do { try { Msg replyMessage = this.serverInfo.Connection.Request(subject, data, timeout); return replyMessage.Data; } catch(Exception exception) { if(tryCount >= 3) { throw exception; } } tryCount++; } while(true); } } #endregion #region 메시지 요청하기 - RequestMessage(subject, message, timeout) /// <summary> /// 메시지 요청하기 /// </summary> /// <param name="subject">수신 서브젝트</param> /// <param name="message">송신 메시지</param> /// <param name="timeout">타임아웃 (디폴트 : 3초)</param> /// <returns>응답 메시지</returns> public string RequestMessage(string subject, string message, int timeout = 3000) { byte[] data = Encoding.UTF8.GetBytes(message); byte[] replyData = RequestMessage(subject, data, timeout); string replyMessage = Encoding.UTF8.GetString(replyData); return replyMessage; } #endregion #region 구독하기 - Subscribe(subject, queue) /// <summary> /// 구독하기 /// </summary> /// <param name="subject">서브젝트</param> /// <param name="queue">큐</param> /// <returns>처리 결과</returns> public bool Subscribe(string subject, string queue) { lock(this.syncObject) { string key = SubscriptionInfo.GetKey(subject, queue); if(this.subscriptionInfoDictionary.ContainsKey(key)) { SubscriptionInfo info = this.subscriptionInfoDictionary[key]; if(info.Subscription == null) { info.Subscribe(this.serverInfo.Connection, (sender, e) => { FireReceivedEvent(e); }); return true; } else { return false; } } else { SubscriptionInfo info = new SubscriptionInfo(subject, queue); info.Subscribe(this.serverInfo.Connection, (sender, e) => { FireReceivedEvent(e); }); this.subscriptionInfoDictionary.Add(key, info); return true; } } } #endregion #region 구독 취소하기 - Unsubscribe(subject, queue) /// <summary> /// 구독 취소하기 /// </summary> /// <param name="subject">서브젝트</param> /// <param name="queue">큐</param> /// <returns>처리 결과</returns> public bool Unsubscribe(string subject, string queue) { lock(this.syncObject) { string key = SubscriptionInfo.GetKey(subject, queue); if(this.subscriptionInfoDictionary.ContainsKey(key)) { SubscriptionInfo info = this.subscriptionInfoDictionary[key]; if(info.Subscription == null) { return false; } else { info.Unsubscribe(); return false; } } else { return false; } } } #endregion #region 리소스 해제하기 - Dispose() /// <summary> /// 리소스 해제하기 /// </summary> public void Dispose() { Stop(); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 서버 발견시 이벤트 발생시키기 - FireServerDiscoveredEvent(e) /// <summary> /// 서버 발견시 이벤트 발생시키기 /// </summary> /// <param name="e">이벤트 인자</param> protected void FireServerDiscoveredEvent(ConnEventArgs e) { ServerDiscovered?.Invoke(this, e); } #endregion #region 재연결시 이벤트 발생시키기 - FireReconnectedEvent(e) /// <summary> /// 재연결시 이벤트 발생시키기 /// </summary> /// <param name="e">이벤트 인자</param> protected void FireReconnectedEvent(ConnEventArgs e) { Reconnected?.Invoke(this, e); } #endregion #region 연결 중단시 이벤트 발생시키기 - FireDisconnectedEvent(e) /// <summary> /// 연결 중단시 이벤트 발생시키기 /// </summary> /// <param name="e">이벤트 인자</param> protected void FireDisconnectedEvent(ConnEventArgs e) { Disconnected?.Invoke(this, e); } #endregion #region 폐쇄시 이벤트 발생시키기 - FireClosedEvent(e) /// <summary> /// 폐쇄시 이벤트 발생시키기 /// </summary> /// <param name="e">NATS 연결</param> protected void FireClosedEvent(ConnEventArgs e) { Closed?.Invoke(this, e); } #endregion #region 에러 이벤트 발생시키기 - FireErrorEvent(e) /// <summary> /// 에러 이벤트 발생시키기 /// </summary> /// <param name="e">이벤트 인자</param> protected void FireErrorEvent(ErrEventArgs e) { Error?.Invoke(this, e); } #endregion #region 메시지 수신시 이벤트 발생시키기 - FireMessageReceivedEvent(source) /// <summary> /// 메시지 수신시 이벤트 발생시키기 /// </summary> /// <param name="source">소스 이벤트 인자</param> protected void FireReceivedEvent(MsgHandlerEventArgs source) { ReceivedEventArgs e = new ReceivedEventArgs(source); Received?.Invoke(this, e); if(e.Reply != null && e.ReplyData != null) { e.ArrivalSubcription.Connection.Publish(e.Reply, e.ReplyData); e.ArrivalSubcription.Connection.Flush(); } } #endregion } } |
■ 서버 권한을 설정하는 방법을 보여준다. ▶ 구성 파일
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
authorization { ADMIN = { publish = ">" subscriber = ">" } REQUESTOR = { publish = ["req.foo", "req.bar"] subscriber = "_INBOX.>" } RESPONDER = { publish = "_INBOX.>" subscriber = ["req.foo", "req.bar"] } DEFAULT_PERMISSIONS = { publish = "SANDBOX.*" subscriber = ["PUBLIC.>", "_INBOX.>"] } PASS : abcdefghijklmnopqrstuvwxyz0123456789 users = { { user : joe , password : foo , permissions : $ADMIN } { user : alice , password : bar , permissions : $REQUESTOR } { user : bob , password : $PASS, permissions : $RESPONDER } { user : charlie, password : bar } } } |
※ joe는 ADMIN 권한을 갖는다. 모든 주제를 발행하고 구독할 수 있다. ※
■ NATS 서버를 윈도우즈 서비스로 실행하는 방법을 보여준다. ▶ 윈도우즈 서비스 설치하기
1 2 3 |
sc.exe create gnatsd1 binPath= "d:\NATS\Server01\Bin\gnatsd.exe --config d:\NATS\Server01\Config\server.conf" |
▶ 윈도우즈 서비스 시작하기
1 2 3 |
sc.exe start gnatsd1 |
▶ 윈도우즈 서비스 중단하기
■ 구성 파일을 사용해 서버를 실행하는 방법을 보여준다. ▶ 실행 명령
1 2 3 |
d:\NATS\Server01\Bin\gnatsd.exe --config d:\NATS\Server01\Config\server.conf |
■ 클러스터용 구성 파일을 설정하는 방법을 보여준다. ▶ 구성 파일
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
addr : 192.168.29.100 # 서버 IP 주소를 설정한다. port : 10000 # 서버 포트를 설정한다. http_port : 10001 # 관리용 포트를 설정한다. authorization { user : user1 # 클라이언트 인증용 사용자 ID를 설정한다. password : password1 # 클라이언트 인증용 패스워드를 설정한다. timeout : 1 } cluster { listen : 192.168.29.100:10002 # 클러스터용 서버 주소/포트를 설정한다. authorization { user : user2 # 클러스터 서버간 인증용 사용자 ID를 설정한다. password : password2 # 클러스터 서버간 인증용 패스워드를 설정한다. timeout : 0.5 } # 클러스터 서버 주소/포트를 나열한다. routes = [ nats-route://user2:password2@192.168.29.101:10002, nats-route://user2:password2@192.168.29.102:10002 ] } debug : false trace : true logtime : true log_file : "d:/NATS/Server01/Log/server.log" # 로그 파일 경로를 설정한다. pid_file : "d:/NATS/Server01/Log/server.pid" # 프로세스 파일 경로를 설정한다. max_connections : 100 max_control_line : 512 max_payload : 10485760 # 최대 페이로드 크기를 10MB로 설정한다. write_deadline : "2s" |
■ 사용자/패스워드를 사용해 서버 연결 문자열을 만드는 방법을 보여준다. ▶ 실행 명령
1 2 3 |
nats://user1:password1@192.168.29.100:4222 |
■ 구성 파일에서 복수의 사용자/패스워드를 설정하는 방법을 보여준다. ▶ 구성 파일
1 2 3 4 5 6 7 8 9 10 |
authorization { users = [ { user : user1, password : password1 } { user : user2, password : password2 } ] } |
■ 구성 파일에서 라우터 연결용 단일 사용자/패스워드를 설정하는 방법을 보여준다. ▶ 구성 파일
1 2 3 4 5 6 7 8 9 10 11 |
cluster { authorization { user : user1 password : password1 timeout : 0.5 } } |
■ 구성 파일에서 단일 사용자/패스워드를 설정하는 방법을 보여준다. ▶ 구성 파일
1 2 3 4 5 6 7 8 |
authorization { user : user1 password : password1 timeout : 1 } |
■ NATS 서버를 사용해 메시지 클라이언트를 만드는 방법을 보여준다. [TestReceiver 프로젝트] ▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
using System; using System.Text; using TestCommon; namespace TestReceiver { /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> private static void Main() { MessageClient client = new MessageClient(); ServerInfo serverInfo = new ServerInfo("127.0.0.1:4222", null, null, 2000, null); SubscriptionInfo[] subscriptionInfoArray = new SubscriptionInfo[] { new SubscriptionInfo("foo", null) }; client.MessageReceived += client_MessageReceived; client.Initialize(serverInfo, subscriptionInfoArray); Console.WriteLine("수신 메시지 클라인트를 초기화 했습니다."); client.Start(); Console.WriteLine("수신 메시지 클라이언트를 시작했습니다."); Console.WriteLine("프로그램을 종료하기 위해 아무 키나 눌러 주시기 바랍니다."); Console.ReadKey(false); client.Stop(); Console.WriteLine("수신 메시지 클라이언트를 중단했습니다."); } #endregion #region 클라이언트 메시지 수신시 처리하기 - client_MessageReceived(sender, e) /// <summary> /// 클라이언트 메시지 수신시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void client_MessageReceived(object sender, MessageReceivedEventArgs e) { Console.WriteLine("수신 서브젝트 : {0}", e.Subject ); Console.WriteLine("응답 서브젝트 : {0}", e.ReplySubject); if(!string.IsNullOrEmpty(e.ReplySubject)) { e.ReplyMessageByteArray = Encoding.UTF8.GetBytes("응답 메시지 : " + DateTime.Now.ToString()); } } #endregion } } |
[TestSender 프로젝트] ▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
using System; using TestCommon; namespace TestSender { /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> private static void Main() { MessageClient client = new MessageClient(); ServerInfo serverInfo = new ServerInfo("127.0.0.1:4222", null, null, 2000, null); client.Initialize(serverInfo, null); Console.WriteLine("송신 메시지 클라인트를 초기화 했습니다."); client.Start(); Console.WriteLine("송신 메시지 클라이언트를 시작했습니다."); Console.WriteLine("메시지를 송신하기 위해 아무 키나 눌러 주시기 바랍니다."); Console.ReadKey(false); for(int i = 0; i < 10; i++) { string reply = client.RequestMessage("foo", string.Format("테스트 메시지 : {0}", i + 1), 5000); Console.WriteLine(reply); } Console.WriteLine("프로그램을 종료하기 위해 아무 키나 눌러 주시기 바랍니다."); Console.ReadKey(false); client.Stop(); Console.WriteLine("송신 메시지 클라이언트를 중단했습니다."); } #endregion } } |
TestSolution.zip
■ NATS 서버를 사용해 메시지를 송수신하는 방법을 보여준다. [TestCommon 프로젝트] ▶ MessageReceivedEventArgs.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
using System; using NATS.Client; namespace TestCommon { /// <summary> /// 메시지 수신시 이벤트 인자 /// </summary> public class MessageReceivedEventArgs : EventArgs { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 메시지 /// </summary> private Msg message; /// <summary> /// 응답 데이터 /// </summary> private byte[] replyData; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 주제 - Subject /// <summary> /// 주제 /// </summary> public string Subject { get { return this.message.Subject; } } #endregion #region 응답 - Reply /// <summary> /// 응답 /// </summary> public string Reply { get { return this.message.Reply; } } #endregion #region 데이터 - Data /// <summary> /// 데이터 /// </summary> public byte[] Data { get { return this.message.Data; } } #endregion #region 응답 데이터 - ReplyData /// <summary> /// 응답 데이터 /// </summary> public byte[] ReplyData { get { return this.replyData; } set { this.replyData = value; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MessageReceivedEventArgs(message) /// <summary> /// 생성자 /// </summary> /// <param name="message">메시지</param> public MessageReceivedEventArgs(Msg message) { this.message = message; this.replyData = null; } #endregion } } |
▶ Receiver.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 |
using System; using NATS.Client; namespace TestCommon { /// <summary> /// 수신기 /// </summary> public class Receiver { //////////////////////////////////////////////////////////////////////////////////////////////////// Event ////////////////////////////////////////////////////////////////////////////////////////// Public #region 메시지 수신시 - MessageReceived /// <summary> /// 메시지 수신시 /// </summary> public event EventHandler<MessageReceivedEventArgs> MessageReceived; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 메시지 서버 URL /// </summary> private string messageServerURL = null; /// <summary> /// 메시지 주제 /// </summary> private string messageSubject = null; /// <summary> /// 메시지 큐 /// </summary> private string messageQueue = null; /// <summary> /// 연결 /// </summary> private IConnection connection = null; /// <summary> /// 메시지 핸들러 /// </summary> private EventHandler<MsgHandlerEventArgs> messageHandler = null; /// <summary> /// 비동기 구독 인터페이스 /// </summary> private IAsyncSubscription subscription = null; /// <summary> /// 잠금 객체 /// </summary> private object lockObject = new object(); /// <summary> /// 작업 여부 /// </summary> private bool isWorking = false; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - Receiver() /// <summary> /// 생성자 /// </summary> public Receiver() { } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 초기화 하기 - Initialize(messageServerURL, messageSubject, messageQueue) /// <summary> /// 초기화 하기 /// </summary> /// <param name="messageServerURL">메시지 서버 URL</param> /// <param name="messageSubject">메시지 주제</param> /// <param name="messageQueue">메시지 큐</param> public void Initialize(string messageServerURL, string messageSubject, string messageQueue) { this.messageServerURL = messageServerURL; this.messageSubject = messageSubject; this.messageQueue = messageQueue; Options options = ConnectionFactory.GetDefaultOptions(); options.Url = this.messageServerURL; this.connection = new ConnectionFactory().CreateConnection(options); this.messageHandler = (sender, e) => { lock(this.lockObject) { FireMessageReceivedEvent(e.Message); } }; } #endregion #region 서버 시작하기 - Start() /// <summary> /// 서버 시작하기 /// </summary> public void Start() { if(this.isWorking) { return; } this.isWorking = true; try { this.subscription = this.connection.SubscribeAsync(this.messageSubject, this.messageQueue, this.messageHandler); } catch(Exception exception) { this.isWorking = false; throw exception; } } #endregion #region 서버 중단하기 - Stop() /// <summary> /// 서버 중단하기 /// </summary> public void Stop() { if(!this.isWorking) { return; } this.isWorking = false; lock(this.lockObject) { if(this.subscription != null) { this.subscription.Dispose(); this.connection.Dispose(); } } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 메시지 수신시 이벤트 발생시키기 - FireMessageReceivedEvent(message) /// <summary> /// 메시지 수신시 이벤트 발생시키기 /// </summary> /// <param name="message">메시지</param> protected void FireMessageReceivedEvent(Msg message) { MessageReceivedEventArgs e = new MessageReceivedEventArgs(message); MessageReceived?.Invoke(this, e); if(e.ReplyData != null) { message.ArrivalSubcription.Connection.Publish(message.Reply, e.ReplyData); } } #endregion } } |
▶ Sender.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 |
using System; using System.Text; using NATS.Client; namespace TestCommon { /// <summary> /// 송신기 /// </summary> public class Sender : IDisposable { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 메시지 서버 URL /// </summary> private string messageServerURL = null; /// <summary> /// 메시지 주제 /// </summary> private string messageSubject = null; /// <summary> /// 연결 /// </summary> private IConnection connection = null; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - Sender() /// <summary> /// 생성자 /// </summary> public Sender() { } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 초기화 하기 - Initialize(messageServerURL, messageSubject) /// <summary> /// 초기화 하기 /// </summary> /// <param name="messageServerURL">메시지 서버 URL</param> /// <param name="messageSubject">메시지 주제</param> public void Initialize(string messageServerURL, string messageSubject) { this.messageServerURL = messageServerURL; this.messageSubject = messageSubject; Options options = ConnectionFactory.GetDefaultOptions(); options.Url = this.messageServerURL; this.connection = new ConnectionFactory().CreateConnection(options); } #endregion #region 메시지 송신하기 - SendMessage(source) /// <summary> /// 메시지 송신하기 /// </summary> /// <param name="source">소스 문자열</param> public void SendMessage(string source) { if(this.connection != null) { byte[] sourceByteArray = Encoding.UTF8.GetBytes(source); this.connection.Publish(this.messageSubject, sourceByteArray); this.connection.Flush(); } } #endregion #region 메시지 요청하기 - RequestMessage(source, timeout) /// <summary> /// 메시지 요청하기 /// </summary> /// <param name="source">소스 문자열</param> /// <param name="timeout">타임아웃</param> /// <returns>결과 문자열</returns> public string RequestMessage(string source, int timeout) { if(this.connection != null) { byte[] sourceByteArray = Encoding.UTF8.GetBytes(source); Msg replyMessage = this.connection.Request(this.messageSubject, sourceByteArray, timeout); string reply = Encoding.UTF8.GetString(replyMessage.Data); return reply; } else { return null; } } #endregion #region (IDisposable) 리소스 해제하기 - Dispose() /// <summary> /// 리소스 해제하기 /// </summary> public void Dispose() { if(this.connection != null) { this.connection.Dispose(); } } #endregion } } |
[TestReceiver 프로젝트] ▶
■ 단일 사용자/패스워드를 설정하는 방법을 보여준다. 명령 프롬프트에서 아래 명령을 실행한다. ▶ 실행 명령
1 2 3 |
gnatsd -DV --user someuser --pass somepassword |
■ 디폴트 서버를 실행하는 방법을 보여준다. 명령 프롬프트에서 아래 명령을 실행한다. ▶ 실행 명령
1 2 3 |
gnatsd |
※ 디폴트 포트 : 4222
■ 모니터링 기능을 활성화하는 방법을 보여준다. 명령 프롬프트에서 아래 명령을 실행한다. ▶ 실행 명령
1 2 3 |
gnatsd -m 8222 |
※ 상기 8222 포트를 사용해 모니터링 기능을