github.com/gogf/gf/v2@v2.7.4/os/gcache/gcache_z_example_cache_test.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 7 package gcache_test 8 9 import ( 10 "context" 11 "fmt" 12 "time" 13 14 "github.com/gogf/gf/v2/database/gredis" 15 "github.com/gogf/gf/v2/frame/g" 16 "github.com/gogf/gf/v2/os/gcache" 17 "github.com/gogf/gf/v2/os/gctx" 18 ) 19 20 func ExampleNew() { 21 // Create a cache object, 22 // Of course, you can also easily use the gcache package method directly. 23 c := gcache.New() 24 25 // Set cache without expiration 26 c.Set(ctx, "k1", "v1", 0) 27 28 // Get cache 29 v, _ := c.Get(ctx, "k1") 30 fmt.Println(v) 31 32 // Get cache size 33 n, _ := c.Size(ctx) 34 fmt.Println(n) 35 36 // Does the specified key name exist in the cache 37 b, _ := c.Contains(ctx, "k1") 38 fmt.Println(b) 39 40 // Delete and return the deleted key value 41 fmt.Println(c.Remove(ctx, "k1")) 42 43 // Close the cache object and let the GC reclaim resources 44 45 c.Close(ctx) 46 47 // Output: 48 // v1 49 // 1 50 // true 51 // v1 <nil> 52 } 53 54 func ExampleCache_Set() { 55 // Create a cache object, 56 // Of course, you can also easily use the gcache package method directly 57 c := gcache.New() 58 59 // Set cache without expiration 60 c.Set(ctx, "k1", g.Slice{1, 2, 3, 4, 5, 6, 7, 8, 9}, 0) 61 62 // Get cache 63 fmt.Println(c.Get(ctx, "k1")) 64 65 // Output: 66 // [1,2,3,4,5,6,7,8,9] <nil> 67 } 68 69 func ExampleCache_SetIfNotExist() { 70 // Create a cache object, 71 // Of course, you can also easily use the gcache package method directly 72 c := gcache.New() 73 74 // Write when the key name does not exist, and set the expiration time to 1000 milliseconds 75 k1, err := c.SetIfNotExist(ctx, "k1", "v1", 1000*time.Millisecond) 76 fmt.Println(k1, err) 77 78 // Returns false when the key name already exists 79 k2, err := c.SetIfNotExist(ctx, "k1", "v2", 1000*time.Millisecond) 80 fmt.Println(k2, err) 81 82 // Print the current list of key values 83 keys1, _ := c.Keys(ctx) 84 fmt.Println(keys1) 85 86 // It does not expire if `duration` == 0. It deletes the `key` if `duration` < 0 or given `value` is nil. 87 c.SetIfNotExist(ctx, "k1", 0, -10000) 88 89 // Wait 1.5 second for K1: V1 to expire automatically 90 time.Sleep(1500 * time.Millisecond) 91 92 // Print the current key value pair again and find that K1: V1 has expired 93 keys2, _ := c.Keys(ctx) 94 fmt.Println(keys2) 95 96 // Output: 97 // true <nil> 98 // false <nil> 99 // [k1] 100 // [<nil>] 101 } 102 103 func ExampleCache_SetMap() { 104 // Create a cache object, 105 // Of course, you can also easily use the gcache package method directly 106 c := gcache.New() 107 108 // map[interface{}]interface{} 109 data := g.MapAnyAny{ 110 "k1": "v1", 111 "k2": "v2", 112 "k3": "v3", 113 } 114 115 // Sets batch sets cache with key-value pairs by `data`, which is expired after `duration`. 116 // It does not expire if `duration` == 0. It deletes the keys of `data` if `duration` < 0 or given `value` is nil. 117 c.SetMap(ctx, data, 1000*time.Millisecond) 118 119 // Gets the specified key value 120 v1, _ := c.Get(ctx, "k1") 121 v2, _ := c.Get(ctx, "k2") 122 v3, _ := c.Get(ctx, "k3") 123 124 fmt.Println(v1, v2, v3) 125 126 // Output: 127 // v1 v2 v3 128 } 129 130 func ExampleCache_Size() { 131 // Create a cache object, 132 // Of course, you can also easily use the gcache package method directly 133 c := gcache.New() 134 135 // Add 10 elements without expiration 136 for i := 0; i < 10; i++ { 137 c.Set(ctx, i, i, 0) 138 } 139 140 // Size returns the number of items in the cache. 141 n, _ := c.Size(ctx) 142 fmt.Println(n) 143 144 // Output: 145 // 10 146 } 147 148 func ExampleCache_Update() { 149 // Create a cache object, 150 // Of course, you can also easily use the gcache package method directly 151 c := gcache.New() 152 153 // Sets batch sets cache with key-value pairs by `data`, which is expired after `duration`. 154 // It does not expire if `duration` == 0. It deletes the keys of `data` if `duration` < 0 or given `value` is nil. 155 c.SetMap(ctx, g.MapAnyAny{"k1": "v1", "k2": "v2", "k3": "v3"}, 0) 156 157 // Print the current key value pair 158 k1, _ := c.Get(ctx, "k1") 159 fmt.Println(k1) 160 k2, _ := c.Get(ctx, "k2") 161 fmt.Println(k2) 162 k3, _ := c.Get(ctx, "k3") 163 fmt.Println(k3) 164 165 // Update updates the value of `key` without changing its expiration and returns the old value. 166 re, exist, _ := c.Update(ctx, "k1", "v11") 167 fmt.Println(re, exist) 168 169 // The returned value `exist` is false if the `key` does not exist in the cache. 170 // It does nothing if `key` does not exist in the cache. 171 re1, exist1, _ := c.Update(ctx, "k4", "v44") 172 fmt.Println(re1, exist1) 173 174 kup1, _ := c.Get(ctx, "k1") 175 fmt.Println(kup1) 176 kup2, _ := c.Get(ctx, "k2") 177 fmt.Println(kup2) 178 kup3, _ := c.Get(ctx, "k3") 179 fmt.Println(kup3) 180 181 // Output: 182 // v1 183 // v2 184 // v3 185 // v1 true 186 // false 187 // v11 188 // v2 189 // v3 190 } 191 192 func ExampleCache_UpdateExpire() { 193 // Create a cache object, 194 // Of course, you can also easily use the gcache package method directly 195 c := gcache.New() 196 197 c.Set(ctx, "k1", "v1", 1000*time.Millisecond) 198 expire, _ := c.GetExpire(ctx, "k1") 199 fmt.Println(expire) 200 201 // UpdateExpire updates the expiration of `key` and returns the old expiration duration value. 202 // It returns -1 and does nothing if the `key` does not exist in the cache. 203 c.UpdateExpire(ctx, "k1", 500*time.Millisecond) 204 205 expire1, _ := c.GetExpire(ctx, "k1") 206 fmt.Println(expire1) 207 208 // May Output: 209 // 1s 210 // 500ms 211 } 212 213 func ExampleCache_Values() { 214 // Create a cache object, 215 // Of course, you can also easily use the gcache package method directly 216 c := gcache.New() 217 218 // Write value 219 c.Set(ctx, "k1", g.Map{"k1": "v1", "k2": "v2"}, 0) 220 // c.Set(ctx, "k2", "Here is Value2", 0) 221 // c.Set(ctx, "k3", 111, 0) 222 223 // Values returns all values in the cache as slice. 224 data, _ := c.Values(ctx) 225 fmt.Println(data) 226 227 // May Output: 228 // [map[k1:v1 k2:v2]] 229 } 230 231 func ExampleCache_Close() { 232 // Create a cache object, 233 // Of course, you can also easily use the gcache package method directly 234 c := gcache.New() 235 236 // Set Cache 237 c.Set(ctx, "k1", "v", 0) 238 data, _ := c.Get(ctx, "k1") 239 fmt.Println(data) 240 241 // Close closes the cache if necessary. 242 c.Close(ctx) 243 244 data1, _ := c.Get(ctx, "k1") 245 246 fmt.Println(data1) 247 248 // Output: 249 // v 250 // v 251 } 252 253 func ExampleCache_Contains() { 254 // Create a cache object, 255 // Of course, you can also easily use the gcache package method directly 256 c := gcache.New() 257 258 // Set Cache 259 c.Set(ctx, "k", "v", 0) 260 261 // Contains returns true if `key` exists in the cache, or else returns false. 262 // return true 263 data, _ := c.Contains(ctx, "k") 264 fmt.Println(data) 265 266 // return false 267 data1, _ := c.Contains(ctx, "k1") 268 fmt.Println(data1) 269 270 // Output: 271 // true 272 // false 273 } 274 275 func ExampleCache_Data() { 276 // Create a cache object, 277 // Of course, you can also easily use the gcache package method directly 278 c := gcache.New() 279 280 c.SetMap(ctx, g.MapAnyAny{"k1": "v1"}, 0) 281 282 data, _ := c.Data(ctx) 283 fmt.Println(data) 284 285 // Set Cache 286 c.Set(ctx, "k5", "v5", 0) 287 data1, _ := c.Get(ctx, "k1") 288 fmt.Println(data1) 289 290 // Output: 291 // map[k1:v1] 292 // v1 293 } 294 295 func ExampleCache_Get() { 296 // Create a cache object, 297 // Of course, you can also easily use the gcache package method directly 298 c := gcache.New() 299 300 // Set Cache Object 301 c.Set(ctx, "k1", "v1", 0) 302 303 // Get retrieves and returns the associated value of given `key`. 304 // It returns nil if it does not exist, its value is nil or it's expired. 305 data, _ := c.Get(ctx, "k1") 306 fmt.Println(data) 307 308 // Output: 309 // v1 310 } 311 312 func ExampleCache_GetExpire() { 313 // Create a cache object, 314 // Of course, you can also easily use the gcache package method directly 315 c := gcache.New() 316 317 // Set cache without expiration 318 c.Set(ctx, "k", "v", 10000*time.Millisecond) 319 320 // GetExpire retrieves and returns the expiration of `key` in the cache. 321 // It returns 0 if the `key` does not expire. It returns -1 if the `key` does not exist in the cache. 322 expire, _ := c.GetExpire(ctx, "k") 323 fmt.Println(expire) 324 325 // May Output: 326 // 10s 327 } 328 329 func ExampleCache_GetOrSet() { 330 // Create a cache object, 331 // Of course, you can also easily use the gcache package method directly 332 c := gcache.New() 333 334 // GetOrSet retrieves and returns the value of `key`, or sets `key`-`value` pair and returns `value` 335 // if `key` does not exist in the cache. 336 data, _ := c.GetOrSet(ctx, "k", "v", 10000*time.Millisecond) 337 fmt.Println(data) 338 339 data1, _ := c.Get(ctx, "k") 340 fmt.Println(data1) 341 342 // Output: 343 // v 344 // v 345 346 } 347 348 func ExampleCache_GetOrSetFunc() { 349 // Create a cache object, 350 // Of course, you can also easily use the gcache package method directly 351 c := gcache.New() 352 353 // GetOrSetFunc retrieves and returns the value of `key`, or sets `key` with result of function `f` 354 // and returns its result if `key` does not exist in the cache. 355 c.GetOrSetFunc(ctx, "k1", func(ctx context.Context) (value interface{}, err error) { 356 return "v1", nil 357 }, 10000*time.Millisecond) 358 v, _ := c.Get(ctx, "k1") 359 fmt.Println(v) 360 361 // If func returns nil, no action is taken 362 c.GetOrSetFunc(ctx, "k2", func(ctx context.Context) (value interface{}, err error) { 363 return nil, nil 364 }, 10000*time.Millisecond) 365 v1, _ := c.Get(ctx, "k2") 366 fmt.Println(v1) 367 368 // Output: 369 // v1 370 } 371 372 func ExampleCache_GetOrSetFuncLock() { 373 // Create a cache object, 374 // Of course, you can also easily use the gcache package method directly 375 c := gcache.New() 376 377 // Modify locking Note that the function `f` should be executed within writing mutex lock for concurrent safety purpose. 378 c.GetOrSetFuncLock(ctx, "k1", func(ctx context.Context) (value interface{}, err error) { 379 return "v1", nil 380 }, 0) 381 v, _ := c.Get(ctx, "k1") 382 fmt.Println(v) 383 384 // Modification failed 385 c.GetOrSetFuncLock(ctx, "k1", func(ctx context.Context) (value interface{}, err error) { 386 return "update v1", nil 387 }, 0) 388 v, _ = c.Get(ctx, "k1") 389 fmt.Println(v) 390 391 c.Remove(ctx, g.Slice{"k1"}...) 392 393 // Output: 394 // v1 395 // v1 396 } 397 398 func ExampleCache_Keys() { 399 // Create a cache object, 400 // Of course, you can also easily use the gcache package method directly 401 c := gcache.New() 402 403 c.SetMap(ctx, g.MapAnyAny{"k1": "v1"}, 0) 404 405 // Print the current list of key values 406 keys1, _ := c.Keys(ctx) 407 fmt.Println(keys1) 408 409 // Output: 410 // [k1] 411 } 412 413 func ExampleCache_KeyStrings() { 414 c := gcache.New() 415 416 c.SetMap(ctx, g.MapAnyAny{"k1": "v1", "k2": "v2"}, 0) 417 418 // KeyStrings returns all keys in the cache as string slice. 419 keys, _ := c.KeyStrings(ctx) 420 fmt.Println(keys) 421 422 // May Output: 423 // [k1 k2] 424 } 425 426 func ExampleCache_Remove() { 427 // Create a cache object, 428 // Of course, you can also easily use the gcache package method directly 429 c := gcache.New() 430 431 c.SetMap(ctx, g.MapAnyAny{"k1": "v1", "k2": "v2"}, 0) 432 433 // Remove deletes one or more keys from cache, and returns its value. 434 // If multiple keys are given, it returns the value of the last deleted item. 435 remove, _ := c.Remove(ctx, "k1") 436 fmt.Println(remove) 437 438 data, _ := c.Data(ctx) 439 fmt.Println(data) 440 441 // Output: 442 // v1 443 // map[k2:v2] 444 } 445 446 func ExampleCache_Removes() { 447 // Create a cache object, 448 // Of course, you can also easily use the gcache package method directly 449 c := gcache.New() 450 451 c.SetMap(ctx, g.MapAnyAny{"k1": "v1", "k2": "v2", "k3": "v3", "k4": "v4"}, 0) 452 453 // Remove deletes one or more keys from cache, and returns its value. 454 // If multiple keys are given, it returns the value of the last deleted item. 455 c.Removes(ctx, g.Slice{"k1", "k2", "k3"}) 456 457 data, _ := c.Data(ctx) 458 fmt.Println(data) 459 460 // Output: 461 // map[k4:v4] 462 } 463 464 func ExampleCache_Clear() { 465 // Create a cache object, 466 // Of course, you can also easily use the gcache package method directly 467 c := gcache.New() 468 469 c.SetMap(ctx, g.MapAnyAny{"k1": "v1", "k2": "v2", "k3": "v3", "k4": "v4"}, 0) 470 471 // clears all data of the cache. 472 c.Clear(ctx) 473 474 data, _ := c.Data(ctx) 475 fmt.Println(data) 476 477 // Output: 478 // map[] 479 } 480 481 func ExampleCache_MustGet() { 482 // Intercepting panic exception information 483 // err is empty, so panic is not performed 484 defer func() { 485 if r := recover(); r != nil { 486 fmt.Println("recover...:", r) 487 } 488 }() 489 490 // Create a cache object, 491 // Of course, you can also easily use the gcache package method directly 492 c := gcache.New() 493 494 // Set Cache Object 495 c.Set(ctx, "k1", "v1", 0) 496 497 // MustGet acts like Get, but it panics if any error occurs. 498 k2 := c.MustGet(ctx, "k2") 499 fmt.Println(k2) 500 501 k1 := c.MustGet(ctx, "k1") 502 fmt.Println(k1) 503 504 // Output: 505 // v1 506 } 507 508 func ExampleCache_MustGetOrSet() { 509 // Create a cache object, 510 // Of course, you can also easily use the gcache package method directly 511 c := gcache.New() 512 513 // MustGetOrSet acts like GetOrSet, but it panics if any error occurs. 514 k1 := c.MustGetOrSet(ctx, "k1", "v1", 0) 515 fmt.Println(k1) 516 517 k2 := c.MustGetOrSet(ctx, "k1", "v2", 0) 518 fmt.Println(k2) 519 520 // Output: 521 // v1 522 // v1 523 } 524 525 func ExampleCache_MustGetOrSetFunc() { 526 // Create a cache object, 527 // Of course, you can also easily use the gcache package method directly 528 c := gcache.New() 529 530 // MustGetOrSetFunc acts like GetOrSetFunc, but it panics if any error occurs. 531 c.MustGetOrSetFunc(ctx, "k1", func(ctx context.Context) (value interface{}, err error) { 532 return "v1", nil 533 }, 10000*time.Millisecond) 534 v := c.MustGet(ctx, "k1") 535 fmt.Println(v) 536 537 c.MustGetOrSetFunc(ctx, "k2", func(ctx context.Context) (value interface{}, err error) { 538 return nil, nil 539 }, 10000*time.Millisecond) 540 v1 := c.MustGet(ctx, "k2") 541 fmt.Println(v1) 542 543 // Output: 544 // v1 545 // 546 } 547 548 func ExampleCache_MustGetOrSetFuncLock() { 549 // Create a cache object, 550 // Of course, you can also easily use the gcache package method directly 551 c := gcache.New() 552 553 // MustGetOrSetFuncLock acts like GetOrSetFuncLock, but it panics if any error occurs. 554 c.MustGetOrSetFuncLock(ctx, "k1", func(ctx context.Context) (value interface{}, err error) { 555 return "v1", nil 556 }, 0) 557 v := c.MustGet(ctx, "k1") 558 fmt.Println(v) 559 560 // Modification failed 561 c.MustGetOrSetFuncLock(ctx, "k1", func(ctx context.Context) (value interface{}, err error) { 562 return "update v1", nil 563 }, 0) 564 v = c.MustGet(ctx, "k1") 565 fmt.Println(v) 566 567 // Output: 568 // v1 569 // v1 570 } 571 572 func ExampleCache_MustContains() { 573 574 // Create a cache object, 575 // Of course, you can also easily use the gcache package method directly 576 c := gcache.New() 577 578 // Set Cache 579 c.Set(ctx, "k", "v", 0) 580 581 // MustContains returns true if `key` exists in the cache, or else returns false. 582 // return true 583 data := c.MustContains(ctx, "k") 584 fmt.Println(data) 585 586 // return false 587 data1 := c.MustContains(ctx, "k1") 588 fmt.Println(data1) 589 590 // Output: 591 // true 592 // false 593 } 594 595 func ExampleCache_MustGetExpire() { 596 // Create a cache object, 597 // Of course, you can also easily use the gcache package method directly 598 c := gcache.New() 599 600 // Set cache without expiration 601 c.Set(ctx, "k", "v", 10000*time.Millisecond) 602 603 // MustGetExpire acts like GetExpire, but it panics if any error occurs. 604 expire := c.MustGetExpire(ctx, "k") 605 fmt.Println(expire) 606 607 // May Output: 608 // 10s 609 } 610 611 func ExampleCache_MustSize() { 612 // Create a cache object, 613 // Of course, you can also easily use the gcache package method directly 614 c := gcache.New() 615 616 // Add 10 elements without expiration 617 for i := 0; i < 10; i++ { 618 c.Set(ctx, i, i, 0) 619 } 620 621 // Size returns the number of items in the cache. 622 n := c.MustSize(ctx) 623 fmt.Println(n) 624 625 // Output: 626 // 10 627 } 628 629 func ExampleCache_MustData() { 630 // Create a cache object, 631 // Of course, you can also easily use the gcache package method directly 632 c := gcache.New() 633 634 c.SetMap(ctx, g.MapAnyAny{"k1": "v1", "k2": "v2"}, 0) 635 636 data := c.MustData(ctx) 637 fmt.Println(data) 638 639 // May Output: 640 // map[k1:v1 k2:v2] 641 } 642 643 func ExampleCache_MustKeys() { 644 // Create a cache object, 645 // Of course, you can also easily use the gcache package method directly 646 c := gcache.New() 647 648 c.SetMap(ctx, g.MapAnyAny{"k1": "v1", "k2": "v2"}, 0) 649 650 // MustKeys acts like Keys, but it panics if any error occurs. 651 keys1 := c.MustKeys(ctx) 652 fmt.Println(keys1) 653 654 // May Output: 655 // [k1 k2] 656 657 } 658 659 func ExampleCache_MustKeyStrings() { 660 c := gcache.New() 661 662 c.SetMap(ctx, g.MapAnyAny{"k1": "v1", "k2": "v2"}, 0) 663 664 // MustKeyStrings returns all keys in the cache as string slice. 665 // MustKeyStrings acts like KeyStrings, but it panics if any error occurs. 666 keys := c.MustKeyStrings(ctx) 667 fmt.Println(keys) 668 669 // May Output: 670 // [k1 k2] 671 } 672 673 func ExampleCache_MustValues() { 674 // Create a cache object, 675 // Of course, you can also easily use the gcache package method directly 676 c := gcache.New() 677 678 // Write value 679 c.Set(ctx, "k1", "v1", 0) 680 681 // MustValues returns all values in the cache as slice. 682 data := c.MustValues(ctx) 683 fmt.Println(data) 684 685 // Output: 686 // [v1] 687 } 688 689 func ExampleCache_SetAdapter() { 690 var ( 691 err error 692 ctx = gctx.New() 693 cache = gcache.New() 694 redisConfig = &gredis.Config{ 695 Address: "127.0.0.1:6379", 696 Db: 9, 697 } 698 cacheKey = `key` 699 cacheValue = `value` 700 ) 701 // Create redis client object. 702 redis, err := gredis.New(redisConfig) 703 if err != nil { 704 panic(err) 705 } 706 // Create redis cache adapter and set it to cache object. 707 cache.SetAdapter(gcache.NewAdapterRedis(redis)) 708 709 // Set and Get using cache object. 710 err = cache.Set(ctx, cacheKey, cacheValue, time.Second) 711 if err != nil { 712 panic(err) 713 } 714 fmt.Println(cache.MustGet(ctx, cacheKey).String()) 715 716 // Get using redis client. 717 fmt.Println(redis.MustDo(ctx, "GET", cacheKey).String()) 718 719 // May Output: 720 // value 721 // value 722 } 723 724 func ExampleCache_GetAdapter() { 725 var ( 726 err error 727 ctx = gctx.New() 728 cache = gcache.New() 729 redisConfig = &gredis.Config{ 730 Address: "127.0.0.1:6379", 731 Db: 10, 732 } 733 cacheKey = `key` 734 cacheValue = `value` 735 ) 736 redis, err := gredis.New(redisConfig) 737 if err != nil { 738 panic(err) 739 } 740 cache.SetAdapter(gcache.NewAdapterRedis(redis)) 741 742 // Set and Get using cache object. 743 err = cache.Set(ctx, cacheKey, cacheValue, time.Second) 744 if err != nil { 745 panic(err) 746 } 747 fmt.Println(cache.MustGet(ctx, cacheKey).String()) 748 749 // Get using redis client. 750 v, err := cache.GetAdapter().(*gcache.AdapterRedis).Get(ctx, cacheKey) 751 fmt.Println(err) 752 fmt.Println(v.String()) 753 754 // May Output: 755 // value 756 // <nil> 757 // value 758 }