Using Cassandra as follows to insert data, I am worried that the stuff that is initialized in IntializeCassandra
is no longer around?
var csession gocql.Session
func IntializeCassandra(){
fmt.Println("Intializing Cassandra")
cluster := gocql.NewCluster("10.0.0.60")
cluster.Keyspace = "tickdata"
cluster.Consistency = gocql.Quorum
csession, _ := cluster.CreateSession()
defer csession.Close()
}
func main() {
IntializeCassandra()
}
Later in a function callback, when I try to insert the data into cassandra, I get a null pointer error
func msgHandler(src *net.UDPAddr, n int, b []byte) {
t := time.Now().UTC()
tformat := t.Format("2006-01-02 15:04:05")
md := &MarketData.MD{}
proto.Unmarshal(b[:n], md)
log.Printf("%d %d %d %d %s %.5f %.5f", md.Firm, md.Symbol, md.Expiry, md.Id, tformat, md.Bid, md.Ask)
if err := csession.Query(`INSERT INTO timeseries (firm, symbol, expiry, quote_id, time, bid, ask) VALUES (?, ?, ?, ?, ?, ?, ?)`,
md.Firm, md.Symbol, md.Expiry, md.Id, tformat, md.Bid, md.Ask).Exec(); err != nil {
log.Fatal(err)
}
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x0 pc=0x594687]
I don't think you want defer csession.Close()
where it is. csession.Close()
will be called when IntializeCassandra
is about to return, so that will happen immediately.
EDIT: I just realized there's another big problem with this code. csession, _ := cluster.CreateSession()
creates a local variable named csession
which shadows the global variable. You should use =
instead of :=
.
There are two problems with code: You should check for error here. If it fails, the don't proceed
csession, err := cluster.CreateSession()
if err != nil {
log.Fatal(err)
}
Also you don't need defer session.Close() or session.Close() as it will invalidate and close your connection. Write defer session.Close() in main after returning session from IntializeCassandra to main(). Also you should have a global variable called Csession which can be used anywhere