Connect to Apache Cassandra with Golang
In this article, we will introduce how to connect to a Cassandra cluster using Go. We will start by installing Go and the Go Cassandra driver and then provide simple demo code for connecting remote server (Cassandra) and local program.
Download the Golang programming language
Go to Golang.org and choose an appropriate version to download.
Install Golang
Follow the instructions to install.
Install the Cassandra Golang driver
Open a terminal and run the following command:
go install github.com/gocql/gocql@latest
Install the GoLand IDE
Go to Jetbrains and install the GoLand IDE using the 30 day free trial.
Create a new project
Open GoLand and select ‘New Project’.
Choose a name for your project when prompted. In this example we have chosen the name “my_go_driver” but you can use whatever name you prefer, it shouldn’t affect the process.
If the SDK is “<No SDK>” then point the project to the Go SDK. The SDK should be in the directory /usr/local/go. Once done, click “Create”.
Right click the project name in the side-bar and generate a new Golang file.
In the pop up choose a name for the new Go file. In these examples we’ll be using “driver” as the file name.
Write Sample Code
Take the following sample code and replace the “Public IP” with the public IP addresses used by your cluster. Also replace “Username” and “Password” with your cluster’s authentication settings. To get your cluster’s username and password settings, go to the Instaclustr Console > Log In > Cluster Details > Connection Info > Default Credentials for Password Authentication.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
package main import ( "fmt" "log" "time" "github.com/gocql/gocql" ) func main() { // connect to the cluster cluster := gocql.NewCluster("PublicIP", "PublicIP", "PublicIP") //replace PublicIP with the IP addresses used by your cluster. cluster.Consistency = gocql.Quorum cluster.ProtoVersion = 4 cluster.ConnectTimeout = time.Second * 10 cluster.Authenticator = gocql.PasswordAuthenticator{Username: "Username", Password: "Password", AllowedAuthenticators: []string {"com.instaclustr.cassandra.auth.InstaclustrPasswordAuthenticator"}} //replace the username and password fields with their real settings, you will need to allow the use of the Instaclustr Password Authenticator. session, err := cluster.CreateSession() if err != nil { log.Println(err) return } defer session.Close() // create keyspaces err = session.Query("CREATE KEYSPACE IF NOT EXISTS sleep_centre WITH REPLICATION = {'class' : 'NetworkTopologyStrategy', 'AWS_VPC_US_WEST_2' : 3};").Exec() //Replace AWS_VPC_US_WEST_2 with the name of the DataCentre you are connecting to. if err != nil { log.Println(err) return } // create table err = session.Query("CREATE TABLE IF NOT EXISTS sleep_centre.sleep_study (name text, study_date date, sleep_time_hours float, PRIMARY KEY (name, study_date));").Exec() if err != nil { log.Println(err) return } // insert some practice data err = session.Query("INSERT INTO sleep_centre.sleep_study (name, study_date, sleep_time_hours) VALUES ('James', '2018-01-07', 8.2);").Exec() err = session.Query("INSERT INTO sleep_centre.sleep_study (name, study_date, sleep_time_hours) VALUES ('James', '2018-01-08', 6.4);").Exec() err = session.Query("INSERT INTO sleep_centre.sleep_study (name, study_date, sleep_time_hours) VALUES ('James', '2018-01-09', 7.5);").Exec() err = session.Query("INSERT INTO sleep_centre.sleep_study (name, study_date, sleep_time_hours) VALUES ('Bob', '2018-01-07', 6.6);").Exec() err = session.Query("INSERT INTO sleep_centre.sleep_study (name, study_date, sleep_time_hours) VALUES ('Bob', '2018-01-08', 6.3);").Exec() err = session.Query("INSERT INTO sleep_centre.sleep_study (name, study_date, sleep_time_hours) VALUES ('Bob', '2018-01-09', 6.7);").Exec() err = session.Query("INSERT INTO sleep_centre.sleep_study (name, study_date, sleep_time_hours) VALUES ('Emily', '2018-01-07', 7.2);").Exec() err = session.Query("INSERT INTO sleep_centre.sleep_study (name, study_date, sleep_time_hours) VALUES ('Emily', '2018-01-09', 7.5);").Exec() if err != nil { log.Println(err) return } // Return average sleep time for James var sleep_time_hours float32 sleep_time_output := session.Query("SELECT avg(sleep_time_hours) FROM sleep_centre.sleep_study WHERE name = 'James';").Iter() sleep_time_output.Scan(&sleep_time_hours) fmt.Println("Average sleep time for James was: ", sleep_time_hours, "h") // return average sleep time for group sleep_time_output = session.Query("SELECT avg(sleep_time_hours) FROM sleep_centre.sleep_study;").Iter() sleep_time_output.Scan(&sleep_time_hours) fmt.Println("Average sleep time for the group was: ", sleep_time_hours, "h") } |
Click Run > Run… then press Enter and you should get the following output: