直接上代码吧:

  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "os/signal"
  6. "syscall"
  7. "time"
  8. "github.com/garyburd/redigo/redis"
  9. )
  10. var (
  11. Pool *redis.Pool
  12. )
  13. func init() {
  14. redisHost := ":6379"
  15. Pool = newPool(redisHost)
  16. close()
  17. }
  18. func newPool(server string) *redis.Pool {
  19. return &redis.Pool{
  20. MaxIdle: 3,
  21. IdleTimeout: 240 * time.Second,
  22. Dial: func() (redis.Conn, error) {
  23. c, err := redis.Dial("tcp", server)
  24. c.Do("auth","pUD85cOEvX22")
  25. if err != nil {
  26. return nil, err
  27. }
  28. return c, err
  29. },
  30. TestOnBorrow: func(c redis.Conn, t time.Time) error {
  31. _, err := c.Do("PING")
  32. return err
  33. },
  34. }
  35. }
  36. func close() {
  37. c := make(chan os.Signal, 1)
  38. signal.Notify(c, os.Interrupt)
  39. signal.Notify(c, syscall.SIGTERM)
  40. signal.Notify(c, syscall.SIGKILL)
  41. go func() {
  42. <-c
  43. Pool.Close()
  44. os.Exit(0)
  45. }()
  46. }
  47. func Get(key string) ([]byte, error) {
  48. conn := Pool.Get()
  49. defer conn.Close()
  50. var data []byte
  51. data, err := redis.Bytes(conn.Do("GET", key))
  52. if err != nil {
  53. return data, fmt.Errorf("error get key %s: %v", key, err)
  54. }
  55. return data, err
  56. }
  57. func Set(key string, val string) ([]byte, error) {
  58. conn := Pool.Get()
  59. defer conn.Close()
  60. var data []byte
  61. data, err := redis.Bytes(conn.Do("SET", key, []byte(val)))
  62. if err != nil {
  63. return data, fmt.Errorf("error set key %s: %v", key, err)
  64. }
  65. return data, err
  66. }
  67. func main() {
  68. _, err := Set("test", "this is a test!")
  69. test, err := Get("test")
  70. fmt.Println(string(test), err)
  71. }

分类: web

标签:   golang