Creating a reusable client in Go - is this needed?


#1

Hi all. I’m new to GoLang, and coming from a PHP background, is there a need to create a kind of “Aerospike Instance” which is re-used over and over rather than declaring one on each use?

To give an example, in PHP I would declare something like $aerospikeClient which would either contain null or be an instance of Aerospike - which I can then check… if is_null then I can create an instance and return that, otherwise I just return the instance which has already been created - if that makes sense.

As I’m unsure exactly how GoLang works in this instance, is there a need to do the same, or do I simply create the Client each time?

This is in a web based environment, so HTTP server instance I guess

Thanks


#2

Yes. You should create an AerospikeClient and share it. That instance is goroutine friendly, so you don’t need to worry about its internal state. You should NOT create an instance each time.


#3

Thanks @Khosrow_Afroozeh.

Is there an example of how I would go about doing this - creating an instance I can share and then re-use it. As I said, completely new to GoLang - getting to grips with it, but just trying to understand how it works and the structures etc.

Thanks


#4

You should define a package variable like:

var client *AerospikeClient

then in you main function, connect to the database:

func main() {
  var err error
  if client, err = as.NewClient('127.0.0.1', 3000); err != nil {
    // handle connection error here
  }

  // your client instance is ready, use it, pass it other functions, etc.

You can have a look at the examples folder, or you can also read the tests to see how these operations are done.

Don’t hesitate to ask in case you had more questions.


#5

That’s great, thanks @Khosrow_Afroozeh - that’s not far off what I’ve done already, so I’m glad I was on the right tracks. Perfect, thank you!