1. go操作memcached

go使用memcached需要第三方的驱动库,这里有一个库是memcached作者亲自实现的,代码质量效率肯定会有保障

1.1.1. 安装

  1. go get github.com/bradfitz/gomemcache/memcache

1.1.2. 使用

  1. import "github.com/bradfitz/gomemcache/memcache"

1.1.3. 栗子(吃的那种)

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/bradfitz/gomemcache/memcache"
  5. )
  6. var (
  7. server = "127.0.0.1:11211"
  8. )
  9. func main() {
  10. //create a handle
  11. mc := memcache.New(server)
  12. if mc == nil {
  13. fmt.Println("memcache New failed")
  14. }
  15. //set key-value
  16. mc.Set(&memcache.Item{Key: "foo", Value: []byte("my value")})
  17. //get key's value
  18. it, _ := mc.Get("foo")
  19. if string(it.Key) == "foo" {
  20. fmt.Println("value is ", string(it.Value))
  21. } else {
  22. fmt.Println("Get failed")
  23. }
  24. ///Add a new key-value
  25. mc.Add(&memcache.Item{Key: "foo", Value: []byte("bluegogo")})
  26. it, err := mc.Get("foo")
  27. if err != nil {
  28. fmt.Println("Add failed")
  29. } else {
  30. if string(it.Key) == "foo" {
  31. fmt.Println("Add value is ", string(it.Value))
  32. } else {
  33. fmt.Println("Get failed")
  34. }
  35. }
  36. //replace a key's value
  37. mc.Replace(&memcache.Item{Key: "foo", Value: []byte("mobike")})
  38. it, err = mc.Get("foo")
  39. if err != nil {
  40. fmt.Println("Replace failed")
  41. } else {
  42. if string(it.Key) == "foo" {
  43. fmt.Println("Replace value is ", string(it.Value))
  44. } else {
  45. fmt.Println("Replace failed")
  46. }
  47. }
  48. //delete an exist key
  49. err = mc.Delete("foo")
  50. if err != nil {
  51. fmt.Println("Delete failed:", err.Error())
  52. }
  53. //incrby
  54. err = mc.Set(&memcache.Item{Key: "aaa", Value: []byte("1")})
  55. if err != nil {
  56. fmt.Println("Set failed :", err.Error())
  57. }
  58. it, err = mc.Get("foo")
  59. if err != nil {
  60. fmt.Println("Get failed ", err.Error())
  61. } else {
  62. fmt.Println("src value is:", it.Value)
  63. }
  64. value, err := mc.Increment("aaa", 7)
  65. if err != nil {
  66. fmt.Println("Increment failed")
  67. } else {
  68. fmt.Println("after increment the value is :", value)
  69. }
  70. //decrby
  71. value, err = mc.Decrement("aaa", 4)
  72. if err != nil {
  73. fmt.Println("Decrement failed", err.Error())
  74. } else {
  75. fmt.Println("after decrement the value is ", value)
  76. }
  77. }