golang利用http模块构建redis读写查api
前沿: 这两天试着用golang做一些高性能的api,不想把压力到聚合在平台的接口上。平台因为要做很多耗时间的操作,uwsgi下会出现少许错误,找了一圈不知道如何解决该问题。 暂时先绕道而行,先拿简单的接口来做测试,慢慢的把复杂的操作也迁移到golang上。 话
前沿:
这两天试着用golang做一些高性能的api,不想把压力到聚合在平台的接口上。平台因为要做很多耗时间的操作,uwsgi下会出现少许错误,找了一圈不知道如何解决该问题。 暂时先绕道而行,先拿简单的接口来做测试,慢慢的把复杂的操作也迁移到golang上。
话说以前高性能的接口,我用的最多的方案还是nginx lua的组合,超强,大家可以看看我以前写的nginx lua的文章,各方面没得说。只是这段时间正在看golang 的,就试着用golang实现redis的api,先来个简单的试试手。
先搞下golang的redis模块
cd $GOPATH/src git clone git://github.com/alphazero/Go-Redis.git redis cd redis go install
简单说下golang操作redis的例子
//xiaorui.cc package main import ( "os"; "bufio"; "log"; "fmt"; "redis"; ) /* hello world, redis style. */ func main () { // create the client. Here we are using a synchronous client. // Using the default ConnectionSpec, we are specifying the client to connect // to db 13 (e.g. SELECT 13), and a password of go-redis (e.g. AUTH go-redis) spec := redis.DefaultSpec().Db(13).Password("go-redis"); client, e := redis.NewSynchClientWithSpec (spec); if e != nil { log.Println ("failed to create the client", e); return } key := "examples/hello/user.name"; value, e := client.Get(key); if e!= nil { log.Println ("error on Get", e); return } if value == nil { fmt.Printf("\nHello, don't believe we've met before!\nYour name? "); reader:= bufio.NewReader(os.Stdin); user, _ := reader.ReadString(byte('\n')); if len(user) > 1 { user = user[0:len(user)-1]; value = []byte(user); client.Set(key, value); } else { fmt.Printf ("vafanculo!\n"); return; } } fmt.Printf ("Hey, ciao %s!\n", fmt.Sprintf("%s", value)); }
我写的实例,大家看懂了后,完全可以做更多的扩展。
其实golang自带的http很有mvc的感觉,三者做了一些分离,很像python里面的web.py tornado。。。
测试结果:
服务端的启动
客户端的测试
//xiaorui.cc package main import( "fmt" "net/http" "io/ioutil" "log" "time" "redis" ) //xiaorui.cc const AddForm = ` Name: Age: ` const setform = ` key: value: ` func Handler( w http.ResponseWriter,r *http.Request ){ path := r.URL.Path[1:] if path == "favicon.ico" { http.NotFound(w, r) return } if path == ""{ path = "index.html" } contents,err:= ioutil.ReadFile( path ) if err !=nil{ fmt.Fprintf( w,"404" ) return } fmt.Fprintf( w,"%s\n",contents ) } func Add( w http.ResponseWriter,r *http.Request ){ name := r.FormValue("name") age := r.FormValue("age") if name == "" || age == "" { fmt.Fprint(w, AddForm) return } fmt.Fprintf(w, "Save : Your name is %s , You age is %s",name,age) } func redisset( w http.ResponseWriter,r *http.Request ){ key := r.FormValue("key") value := r.FormValue("value") if key == "" || value == "" { fmt.Fprint(w, setform) return } spec := redis.DefaultSpec().Db(0).Password(""); client, e := redis.NewSynchClientWithSpec (spec); if e != nil { log.Println ("服务器连接有异常", e); return } inva := []byte(value) client.Set(key, inva); fmt.Fprintf(w, "哥们,你输入的key %s 和value %s 已经插入到redis里面了",key,key) } func redisget( w http.ResponseWriter,r *http.Request ){ key := r.FormValue("key") if key == "" { fmt.Fprint(w, setform) return } spec := redis.DefaultSpec().Db(0).Password(""); client, e := redis.NewSynchClientWithSpec (spec); if e != nil { log.Println ("服务器连接有异常", e); return } value, e := client.Get(key); fmt.Fprintf(w, "哥们,你要查询的key %s 和value %s ",key,value) } func valueget(w http.ResponseWriter, r *http.Request) { params := r.URL.Query() user := params.Get("user") fmt.Fprintf(w, "you are get user %s", user) } func main(){ http.HandleFunc( "/",Handler) http.HandleFunc( "/add",Add) http.HandleFunc( "/redisset",redisset) http.HandleFunc( "/redisget",redisget) http.HandleFunc( "/valueget",valueget) s := &http.Server{ Addr: ":80", ReadTimeout: 30 * time.Second, WriteTimeout: 30 * time.Second, MaxHeaderBytes: 1 <p> </p> <p style="color:#555555;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;"> <span style="font-family:微软雅黑, 'microsoft yahei';font-size:20px;"><br> </span> </p> <p style="color:#555555;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;"> <span style="font-family:微软雅黑, 'microsoft yahei';font-size:20px;"><br> </span> </p> <p> </p> <p style="color:#555555;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;"> <span style="font-family:微软雅黑, 'microsoft yahei';font-size:20px;"><br> </span> </p> <p style="color:#555555;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;"> <span style="font-family:微软雅黑, 'microsoft yahei';font-size:20px;"><br> </span> </p> <p style="color:#555555;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;"> <span style="font-family:微软雅黑, 'microsoft yahei';font-size:20px;"><br> </span></p> <p class="copyright"> 原文地址:golang利用http模块构建redis读写查api, 感谢原作者分享。 </p>

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

On CentOS systems, you can limit the execution time of Lua scripts by modifying Redis configuration files or using Redis commands to prevent malicious scripts from consuming too much resources. Method 1: Modify the Redis configuration file and locate the Redis configuration file: The Redis configuration file is usually located in /etc/redis/redis.conf. Edit configuration file: Open the configuration file using a text editor (such as vi or nano): sudovi/etc/redis/redis.conf Set the Lua script execution time limit: Add or modify the following lines in the configuration file to set the maximum execution time of the Lua script (unit: milliseconds)

Use the Redis command line tool (redis-cli) to manage and operate Redis through the following steps: Connect to the server, specify the address and port. Send commands to the server using the command name and parameters. Use the HELP command to view help information for a specific command. Use the QUIT command to exit the command line tool.

In Debian systems, readdir system calls are used to read directory contents. If its performance is not good, try the following optimization strategy: Simplify the number of directory files: Split large directories into multiple small directories as much as possible, reducing the number of items processed per readdir call. Enable directory content caching: build a cache mechanism, update the cache regularly or when directory content changes, and reduce frequent calls to readdir. Memory caches (such as Memcached or Redis) or local caches (such as files or databases) can be considered. Adopt efficient data structure: If you implement directory traversal by yourself, select more efficient data structures (such as hash tables instead of linear search) to store and access directory information

To improve the performance of PostgreSQL database in Debian systems, it is necessary to comprehensively consider hardware, configuration, indexing, query and other aspects. The following strategies can effectively optimize database performance: 1. Hardware resource optimization memory expansion: Adequate memory is crucial to cache data and indexes. High-speed storage: Using SSD SSD drives can significantly improve I/O performance. Multi-core processor: Make full use of multi-core processors to implement parallel query processing. 2. Database parameter tuning shared_buffers: According to the system memory size setting, it is recommended to set it to 25%-40% of system memory. work_mem: Controls the memory of sorting and hashing operations, usually set to 64MB to 256M

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.
