Home  >  Article  >  Backend Development  >  Using Apache Cassandra in Go: A Complete Guide

Using Apache Cassandra in Go: A Complete Guide

PHPz
PHPzOriginal
2023-06-18 19:56:541662browse

Apache Cassandra is a non-relational database (NoSQL) that is widely used in large-scale, high-throughput and fault-tolerant distributed data storage scenarios. It uses a data model similar to Google's Bigtable and combines it with Amazon Dynamo's distributed architecture. In this article, we will discuss how to use Apache Cassandra in Go language and how to use it to build a simple web application.

Cassandra’s data model

Cassandra’s data model can be logically viewed as a fully distributed hash table. The table consists of multiple column families. Each column family contains a keyspace (Keyspace), which contains multiple tables (Table). Each table contains many rows (Row), and in each row, it can Store multiple data named columns (Column).

In Cassandra, you can use CQL (Cassandra Query Language) to query and manipulate data. CQL is easy to learn and use because it uses a syntax similar to the SQL language, but some syntax details are still different.

Steps to use Apache Cassandra

Now, let’s take a look at how to use Apache Cassandra in your Go application. There are mainly 5 steps below.

1. Install Cassandra

The first thing to do is to install Cassandra. You can go to Cassandra's official website to download the corresponding binary file and install it according to the instructions.

2. Create a column family

After you have installed Cassandra, the next step is to create a column family and add some columns to the column family. You can use cqlsh (Cassandra shell) to operate Cassandra.

Here, we created a column family named "student", which contains student name, student number, class and other information:

CREATE KEYSPACE learning WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '3'} AND durable_writes = true;

CREATE TABLE learning.students (
   student_id text PRIMARY KEY,
   first_name text,
   last_name text,
   department text
);

3. Connect to Cassandra

In Go language, you can use third-party libraries to connect to Cassandra. Here, we use gocql to connect.

The following is a code example to connect to a Cassandra cluster:

cluster := gocql.NewCluster("127.0.0.1")
cluster.Keyspace = "learning"
session, err := cluster.CreateSession()
if err != nil {
    log.Fatal(err)
}
defer session.Close()

Here, you simply specify the IP address or hostname of the Cassandra cluster and specify the keyspace to connect to.

4. Write query statements

In Go language, you can use gocql.Query to write query statements. The following is a code example for querying all student information in the table:

var students []model.Student

query := "SELECT * FROM students"
iter := session.Query(query).Iter()

for iter.Scan(&student.ID, &student.FirstName, &student.LastName, &student.Department) {
    students = append(students, student)
}

if err := iter.Close(); err != nil {
    log.Fatal(err)
}

for _, student := range students {
    fmt.Println(student.ID, student.FirstName, student.LastName, student.Department)
}

Here, we first declare a model.Student structure to store the student data retrieved from the table. Then, we wrote a SELECT query statement and created a query object using the session.Query method. Next, we iterate over the results of the query and store the data into a slice, and finally output the information for all students.

5. Close the connection

Finally, we need to close the connection to Cassandra. The following is a code example to close the Cassandra connection:

defer session.Close()

Building a Web Application using Cassandra

Now, let us see how to use Apache Cassandra in the Go language to build a simple web application. In this web application, we will create a student list page, display the information of all students, and provide a form to add student information.

Here we use the Gin framework to build web applications. The following is a code example for building a Web application:

package main

import (
    "html/template"
    "log"
    "net/http"
    "strconv"

    "github.com/gin-gonic/gin"
    "github.com/gocql/gocql"
)

type Student struct {
    ID         string
    FirstName  string
    LastName   string
    Department string
}

var session *gocql.Session

func init() {
    cluster := gocql.NewCluster("127.0.0.1")
    cluster.Keyspace = "learning"
    var err error
    session, err = cluster.CreateSession()
    if err != nil {
        log.Fatal(err)
    }
}

func main() {
    router := gin.Default()

    router.LoadHTMLGlob("templates/*")

    router.GET("/", func(c *gin.Context) {
        var students []Student

        query := "SELECT * FROM students"
        iter := session.Query(query).Iter()

        for {
            var student Student
            if !iter.Scan(&student.ID, &student.FirstName, &student.LastName, &student.Department) {
                break
            }
            students = append(students, student)
        }

        if err := iter.Close(); err != nil {
            log.Fatal(err)
        }

        c.HTML(http.StatusOK, "index.tmpl", gin.H{
            "students": students,
        })
    })

    router.POST("/add", func(c *gin.Context) {
        student := Student{
            ID:         c.PostForm("id"),
            FirstName:  c.PostForm("first_name"),
            LastName:   c.PostForm("last_name"),
            Department: c.PostForm("department"),
        }

        query := "INSERT INTO students (student_id, first_name, last_name, department) VALUES (?, ?, ?, ?)"
        err := session.Query(query, student.ID, student.FirstName, student.LastName, student.Department).Exec()
        if err != nil {
            log.Fatal(err)
        }

        c.Redirect(http.StatusFound, "/")
    })

    router.Run(":8080")
}

Here, we first declare a structure named Student, which is used to represent a student's information. Then, we connect to the Cassandra cluster in the init function.

In the main function, we use Gin routing to handle different HTTP requests. On the "/" path, we first query the information of all students and pass them to the index.tmpl template for rendering the student list page. On the "/add" path, we insert a new student record based on the form data submitted by the user, and then redirect the user back to the student list page.

Finally, we call router.Run() to start the web application.

Summary

In this article, we discussed how to use Apache Cassandra in Go language and built a simple web application. Through this example, we can see the simple usage of Cassandra and how to use third-party libraries to operate Cassandra in Go language. If you are looking for a high throughput and high availability distributed database, then Apache Cassandra may be an option for you.

The above is the detailed content of Using Apache Cassandra in Go: A Complete Guide. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn