Go实战--也许最快的Go语言Web框架kataras/iris初识三(Redis、leveldb、BoltDB)

生命不止,继续 go go go !!!

之前介绍了iris框架,介绍了如何使用basic认证、Markdown、YAML、Json等: 
Go实战–也许最快的Go语言Web框架kataras/iris初识(basic认证、Markdown、YAML、Json)

介绍了如何使用TOML、Cache、Cookie等: 
Go实战–也许最快的Go语言Web框架kataras/iris初识二(TOML、Cache、Cookie)

继续跟大家一起学习iris框架.

Redis

关于redis,之前也有介绍过: 
Go实战–golang中使用redis(redigo和go-redis/redis)

Go实战–通过httprouter和redis框架搭建restful api服务(github.com/julienschmidt/httprouter)

启动Windows上redis服务

credis-server.exe redis.windows.conf

如果出现[9376] 25 Oct 15:09:11.726 # Creating Server TCP listening socket 127.0.0.1:6379: bind: No error,证明启动成功。

main.go:

package main

import (
    "time"

    "github.com/kataras/iris"
    "github.com/kataras/iris/context"

    "github.com/kataras/iris/sessions"
    "github.com/kataras/iris/sessions/sessiondb/redis"
    "github.com/kataras/iris/sessions/sessiondb/redis/service"
)

func main() {
    db := redis.New(service.Config{
        Network:     "tcp",
        Addr:        "127.0.0.1:6379",
        Password:    "",
        Database:    "",
        MaxIdle:     0,
        MaxActive:   10,
        IdleTimeout: service.DefaultRedisIdleTimeout,
        Prefix:      ""}) // optionally configure the bridge between your redis server

    // use go routines to query the database
    db.Async(true)
    // close connection when control+C/cmd+C
    iris.RegisterOnInterrupt(func() {
        db.Close()
    })

    sess := sessions.New(sessions.Config{Cookie: "sessionscookieid", Expires: 45 * time.Minute})

    sess.UseDatabase(db)

    // the rest of the code stays the same.
    app := iris.New()

    app.Get("/", func(ctx context.Context) {
        ctx.Writef("You should navigate to the /set, /get, /delete, /clear,/destroy instead")
    })
    app.Get("/set", func(ctx context.Context) {
        s := sess.Start(ctx)
        //set session values
        s.Set("name", "iris")

        //test if setted here
        ctx.Writef("All ok session setted to: %s", s.GetString("name"))
    })

    app.Get("/get", func(ctx context.Context) {
        // get a specific key, as string, if no found returns just an empty string
        name := sess.Start(ctx).GetString("name")

        ctx.Writef("The name on the /set was: %s", name)
    })

    app.Get("/delete", func(ctx context.Context) {
        // delete a specific key
        sess.Start(ctx).Delete("name")
    })

    app.Get("/clear", func(ctx context.Context) {
        // removes all entries
        sess.Start(ctx).Clear()
    })

    app.Get("/destroy", func(ctx context.Context) {
        //destroy, removes the entire session data and cookie
        sess.Destroy(ctx)
    })

    app.Get("/update", func(ctx context.Context) {
        // updates expire date with a new date
        sess.ShiftExpiration(ctx)
    })

    app.Run(iris.Addr(":8080"))
}

浏览器输入:localhost:8080/set

查看redis:

127.0.0.1:6379> keys *
1) "be019530-7f60-4a52-8e0b-81bc27cc8b9a"
127.0.0.1:6379> get be019530-7f60-4a52-8e0b-81bc27cc8b9a
"3\xff\x81\x03\x01\x01\x0bRemoteStore\x01\xff\x82\x00\x01\x02\x01\x06Values\x01\xff\x86\x00\x01\bLifetime\x01\xff\x88\x00\x00\x00\x14\xff\x85\x02\x01\x01\x05Store\x01\xff\x86\x00\x01\xff\x84\x00\x00(\xff\x83\x03\x01\x01\x05Entry\x01\xff\x84\x00\x01\x02\x01\x03Key\x01\x0c\x00\x01\bValueRaw\x01\x10\x00\x00\x00\x14\xff\x87\x05\x01\x01\bLifeTime\x01\xff\x88\x00\x00\x00\x10\xff\x89\x05\x01\x01\x04Time\x01\xff\x8a\x00\x00\x00-\xff\x82\x01\x01\x01\x04name\x01\x06string\x0c\x06\x00\x04iris\x00\x01\x0f\x01\x00\x00\x00\x0e\xd1\x82QK,\xd7\x86\x98\x01\xe0\x00"
127.0.0.1:6379>

leveldb

LevelDB是一个由Google公司所研发的键/值对(Key/Value Pair)嵌入式数据库管理系统编程库.

syndtr/goleveldb 
这是golang中比较有名的关于leveldb的库,我们有机会之后再学习。

main.go:

package main

import (
    "time"

    "github.com/kataras/iris"
    "github.com/kataras/iris/context"

    "github.com/kataras/iris/sessions"
    "github.com/kataras/iris/sessions/sessiondb/leveldb"
)

func main() {
    db, _ := leveldb.New("./")

    // use different go routines to sync the database
    db.Async(true)

    // close and unlock the database when control+C/cmd+C pressed
    iris.RegisterOnInterrupt(func() {
        db.Close()
    })

    sess := sessions.New(sessions.Config{
        Cookie:  "sessionscookieid",
        Expires: 45 * time.Minute, // <=0 means unlimited life
    })

    //
    // IMPORTANT:
    //
    sess.UseDatabase(db)

    // the rest of the code stays the same.
    app := iris.New()

    app.Get("/", func(ctx context.Context) {
        ctx.Writef("You should navigate to the /set, /get, /delete, /clear,/destroy instead")
    })
    app.Get("/set", func(ctx context.Context) {
        s := sess.Start(ctx)
        //set session values
        s.Set("name", "iris")

        //test if setted here
        ctx.Writef("All ok session setted to: %s", s.GetString("name"))
    })

    app.Get("/set/{key}/{value}", func(ctx context.Context) {
        key, value := ctx.Params().Get("key"), ctx.Params().Get("value")
        s := sess.Start(ctx)
        // set session values
        s.Set(key, value)

        // test if setted here
        ctx.Writef("All ok session setted to: %s", s.GetString(key))
    })

    app.Get("/get", func(ctx context.Context) {
        // get a specific key, as string, if no found returns just an empty string
        name := sess.Start(ctx).GetString("name")

        ctx.Writef("The name on the /set was: %s", name)
    })

    app.Get("/get/{key}", func(ctx context.Context) {
        // get a specific key, as string, if no found returns just an empty string
        name := sess.Start(ctx).GetString(ctx.Params().Get("key"))

        ctx.Writef("The name on the /set was: %s", name)
    })

    app.Get("/delete", func(ctx context.Context) {
        // delete a specific key
        sess.Start(ctx).Delete("name")
    })

    app.Get("/clear", func(ctx context.Context) {
        // removes all entries
        sess.Start(ctx).Clear()
    })

    app.Get("/destroy", func(ctx context.Context) {
        //destroy, removes the entire session data and cookie
        sess.Destroy(ctx)
    })

    app.Get("/update", func(ctx context.Context) {
        // updates expire date with a new date
        sess.ShiftExpiration(ctx)
    })

    app.Run(iris.Addr(":8080"))
}

运行后,查看文件夹: 
这里写图片描述

BoltDB

BoltDB是一个嵌入式key/value的数据库,即只需要将其链接到你的应用程序代码中即可使用BoltDB提供的API来高效的存取数据。而且BoltDB支持完全可序列化的ACID事务,让应用程序可以更简单的处理复杂操作。

BoltDB设计源于LMDB,具有以下特点:

直接使用API存取数据,没有查询语句; 
支持完全可序列化的ACID事务,这个特性比LevelDB强; 
数据保存在内存映射的文件里。没有wal、线程压缩和垃圾回收; 
通过COW技术,可实现无锁的读写并发,但是无法实现无锁的写写并发,这就注定了读性能超高,但写性能一般,适合与读多写少的场景。 
最后,BoltDB使用Golang开发,而且被应用于influxDB项目作为底层存储。

LevelDB和BoltDB的不同 
LevelDB是Google开发的,也是一个k/v的存储数据库,和BoltDB比起起来有很大的不同。对于使用者而言,最大的不同就是LevelDB没有事务。在其内部,也有很多的不同:LevelDB实现了一个日志结构化的merge tree。它将有序的key/value存储在不同文件的之中,并通过“层级”把它们分开,并且周期性地将小的文件merge为更大的文件。这让其在随机写的时候会很快,但是读的时候却很慢。这也让LevelDB的性能不可预知:但数据量很小的时候,它可能性能很好,但是当随着数据量的增加,性能只会越来越糟糕。而且做merge的线程也会在服务器上出现问题。LevelDB是C++写的,但是也有些Go的实现方式,如syndtr/goleveldb、leveldb-go。

BoltDB使用一个单独的内存映射的文件,实现一个写入时拷贝的B+树,这能让读取更快。而且,BoltDB的载入时间很快,特别是在从crash恢复的时候,因为它不需要去通过读log(其实它压根也没有)去找到上次成功的事务,它仅仅从两个B+树的根节点读取ID。

github地址: 
https://github.com/boltdb/bolt

Star: 7144

获取: 
go get github.com/boltdb/bolt/…

iris中使用boltDB:

package main

import (
    "time"

    "github.com/kataras/iris"
    "github.com/kataras/iris/context"

    "github.com/kataras/iris/sessions"
    "github.com/kataras/iris/sessions/sessiondb/boltdb"
)

func main() {
    db, _ := boltdb.New("./sessions.db", 0666, "users")
    // use different go routines to sync the database
    db.Async(true)

    // close and unlock the database when control+C/cmd+C pressed
    iris.RegisterOnInterrupt(func() {
        db.Close()
    })

    sess := sessions.New(sessions.Config{
        Cookie:  "sessionscookieid",
        Expires: 45 * time.Minute, // <=0 means unlimited life
    })

    //
    // IMPORTANT:
    //
    sess.UseDatabase(db)

    // the rest of the code stays the same.
    app := iris.New()

    app.Get("/", func(ctx context.Context) {
        ctx.Writef("You should navigate to the /set, /get, /delete, /clear,/destroy instead")
    })
    app.Get("/set", func(ctx context.Context) {
        s := sess.Start(ctx)
        //set session values
        s.Set("name", "iris")

        //test if setted here
        ctx.Writef("All ok session setted to: %s", s.GetString("name"))
    })

    app.Get("/set/{key}/{value}", func(ctx context.Context) {
        key, value := ctx.Params().Get("key"), ctx.Params().Get("value")
        s := sess.Start(ctx)
        // set session values
        s.Set(key, value)

        // test if setted here
        ctx.Writef("All ok session setted to: %s", s.GetString(key))
    })

    app.Get("/get", func(ctx context.Context) {
        // get a specific key, as string, if no found returns just an empty string
        name := sess.Start(ctx).GetString("name")

        ctx.Writef("The name on the /set was: %s", name)
    })

    app.Get("/get/{key}", func(ctx context.Context) {
        // get a specific key, as string, if no found returns just an empty string
        name := sess.Start(ctx).GetString(ctx.Params().Get("key"))

        ctx.Writef("The name on the /set was: %s", name)
    })

    app.Get("/delete", func(ctx context.Context) {
        // delete a specific key
        sess.Start(ctx).Delete("name")
    })

    app.Get("/clear", func(ctx context.Context) {
        // removes all entries
        sess.Start(ctx).Clear()
    })

    app.Get("/destroy", func(ctx context.Context) {
        //destroy, removes the entire session data and cookie
        sess.Destroy(ctx)
    })

    app.Get("/update", func(ctx context.Context) {
        // updates expire date with a new date
        sess.ShiftExpiration(ctx)
    })

    app.Run(iris.Addr(":8080"))
}

猜你喜欢

转载自blog.csdn.net/zl1zl2zl3/article/details/79785852