duanrong6802 2019-03-22 03:26
浏览 68
已采纳

Singleton实例继续在Go中创建新实例

I am using redis to store sessions for my Go simple web app. For this, I only want a single session to access the redis connection at a time. I searched up on implementing singleton objects in Go and followed. This is the code I'm currently implementing:

Redis connection:

package Datab

import (
    "github.com/gomodule/redigo/redis"
)

type cache struct {
    Conn redis.Conn
}

var singleCache *cache = nil

func GetSessionCache() *cache {

    if singleCache == nil {

        singleCache := &cache{}
        singleCache.Conn, _ = redis.DialURL("redis://localhost")
        // ^ SINGLECACHE IS NOT NIL HERE.

    }
    return singleCache
    // ^ SAYS THIS IS NIL!

}

Redis Implementation:

package Handler

import (
    Datab "videodoox/DB" // this file contains the redis connection implementation
)

connStru := *Datab.GetSessionCache()
cache := connStru.Conn

connStru2 := *Datab.GetSessionCache()
cache2: = connStru.Conn
// ^ THIS CONNECTION HERE IS A COMPLETELY NEW INSTANCE.

Everytime I get the connection, the redis connection file creates a new instance of the connection. How do I create a new connection once and just return that connection everytime? Thanks!

  • 写回答

1条回答 默认 最新

  • dongtuo2373 2019-03-23 03:14
    关注

    Comments to the initial question solve the issue, but just to provide a complete solution your code can look like:

    package Datab
    
    import (
        "sync"
    
        "github.com/gomodule/redigo/redis"
    )
    
    type cache struct {
        Conn redis.Conn
    }
    
    var singleCache *cache
    var initOnce sync.Once
    
    func GetSessionCache() *cache {
        initOnce.Do(func() {
            singleCache := &cache{}
            singleCache.Conn, _ = redis.DialURL("redis://localhost")
        })
    
        return singleCache
    }
    

    Just a couple of extra notes:

    • No need to specify nil as an initial value of pointers, zero value for them is nil by default (var singleCache *cache vs var singleCache *cache = nil).
    • You should handle potential error returned by redis.DialURL and not just skip it with _.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同