KituraRedis is a pure Swift client for interacting with a Redis database.
The latest version of Kitura-redis requires Swift 4.0.3 or later. You can download this version of the Swift binaries by following this link. Compatibility with other Swift versions is not guaranteed.
Add the Kitura-redis
package to the dependencies within your application’s Package.swift
file. Substitute "x.x.x"
with the latest Kitura-redis
release.
.package(url: "https://github.com/Kitura/Kitura-redis.git", from: "x.x.x")
Add SwiftRedis
to your target's dependencies:
.target(name: "example", dependencies: ["SwiftRedis"]),
import SwiftRedis
To test Kitura-redis locally you need to install Redis.
brew install redis
To start redis as a background service and have the service restarted at login:
brew services start redis
Or, if you don't want redis running as a background service:
redis-server /usr/local/etc/redis.conf
This example shows you how to connect and make calls to Redis from Swift.
Create a directory for this project, change into it and then initialize the project:
$ mkdir exampleRedis && cd exampleRedis
$ swift package init --type executable
Add Kitura-redis as a dependency as described above in "Add dependencies".
Now, edit your main.swift
file to contain:
import Foundation
import SwiftRedis
let redis = Redis()
redis.connect(host: "localhost", port: 6379) { (redisError: NSError?) in
if let error = redisError {
print(error)
}
else {
print("Connected to Redis")
// Set a key
redis.set("Redis", value: "on Swift") { (result: Bool, redisError: NSError?) in
if let error = redisError {
print(error)
}
// Get the same key
redis.get("Redis") { (string: RedisString?, redisError: NSError?) in
if let error = redisError {
print(error)
}
else if let string = string?.asString {
print("Redis \(string)")
}
}
}
}
}
Next, build the program and run it (either within Xcode or on the command line):
$ swift build
$ .build/debug/redisExample
You should see:
$ Connected to Redis
$ Redis on Swift
This shows that we've connected to Redis, set a string value for a key and then successfully retrieved the value for that key.
Contributions to the Kitura-redis project are welcome. You will want to be able to test your changes locally before submitting a pull request.
The tests require a Redis server to be accessible locally on the default port (6379). If you do not wish to install Redis permanently, you can use Docker to run a temporary instance locally as follows:
docker run -d -p 6379:6379 redis:alpine redis-server --requirepass password123
The password specified above must match the one defined in Tests/SwiftRedis/password.txt
. Then you can run the tests as normal, either via Xcode or with:
swift test
For more information visit our API reference.
We love to talk server-side Swift, and Kitura. Join our Slack to meet the team!
This library is licensed under Apache 2.0. Full license text is available in LICENSE.