Source

redis-client.egg / redis-client.scm

; chicken-scheme redis-client
; Copyright (C) 2011 A. Carl Douglas
(use socket)

(define (redis-write-command port command args)
  (fprintf port "*~A\r\n$~A\r\n~A\r\n~A~!" 
            (+ 1 (length args))
            (string-length (symbol->string command))
            (symbol->string command)
            (apply string-append 
              (map (lambda(arg)
                     (sprintf "$~A\r\n~A\r\n" (string-length arg) arg)) args))))

(define (redis-read-response port)
  (letrec ((parse (lambda(argc args)
             (if (= argc 0)
               args
               (let ((ch (read-char port)))
                 (case ch
                   ((#\+) (list (read-line port)))
                   ((#\*) (parse (string->number (read-line port)) args))
                   ((#\$) (parse (- argc 1)
                            (append args 
                              (list (read-string (string->number (read-line port)) port)))))
                   ((#\:)       (list (read-line port)))
                   ((#\return)  (parse argc args))
                   ((#\newline) (parse argc args))
                   (else  (error "unrecognised prefix" ch (read-line port)))))))))
            (parse 1 '())))

(define-syntax make-redis-parameter-function
  (lambda (x r c)
    (let ((command-proc (r (string->symbol(sprintf "redis-~A" (cadr x))))))
      `(define (,command-proc . args)
         (redis-write-command (redis-out-port) ',(cadr x) args)
         (redis-read-response (redis-in-port))))))

(define-syntax map-make-redis-parameter-function
  (syntax-rules ()
    ((_ (fn ...)) (begin (make-redis-parameter-function fn) ...))))

(map-make-redis-parameter-function
  (list ping lpush rpop brpop subscribe publish))

(define redis-in-port (make-parameter #f))
(define redis-out-port (make-parameter #f))

(define *redis-socket* '())

(define (redis-connect host port)
  (set! *redis-socket* (socket-connect/ai (address-information "127.0.0.1" 6379 family: af/inet)))
  (define-values (in-port out-port) (socket-i/o-ports *redis-socket*))
  (redis-in-port in-port)
  (redis-out-port out-port)
  (and (port? (redis-in-port)) (port? (redis-out-port))))

; Example program:
;
;(pp (redis-connect "127.0.0.1" 6379))
;(pp (redis-publish "my-queue" "hello world"))
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.