|
3 | 3 | SwiftMemcache is a Swift Package in development that provides a convenient way to communicate with [Memcached](https://github.com/memcached/memcached) servers.
|
4 | 4 |
|
5 | 5 | ## Getting Started
|
| 6 | + |
| 7 | +## Overview |
| 8 | + |
| 9 | +### Memcache Connection API |
| 10 | + |
| 11 | +Our `MemcacheConnection` allows for communicate with a Memcached server. This actor takes care of establishing a connection, creating a request stream and handling asynchronous execution of commands. |
| 12 | + |
| 13 | +Here's an example of how you can use `MemcachedConnection` in a program. |
| 14 | + |
| 15 | +```swift |
| 16 | +@main |
| 17 | +struct Program { |
| 18 | + // Use the shared singleton instance of MultiThreadedEventLoopGroup |
| 19 | + static let eventLoopGroup = MultiThreadedEventLoopGroup.singleton |
| 20 | + // Initialize the logger |
| 21 | + static let logger = Logger(label: "memcache") |
| 22 | + |
| 23 | + static func main() async throws { |
| 24 | + // Instantiate a new MemcacheConnection actor with host, port, and event loop group |
| 25 | + let memcacheConnection = MemcacheConnection(host: "127.0.0.1", port: 11211, eventLoopGroup: eventLoopGroup) |
| 26 | + |
| 27 | + // Initialize the service group |
| 28 | + let serviceGroup = ServiceGroup(services: [memcacheConnection], logger: self.logger) |
| 29 | + |
| 30 | + try await withThrowingTaskGroup(of: Void.self) { group in |
| 31 | + // Add the connection actor's run function to the task group |
| 32 | + // This opens the connection and handles requests until the task is cancelled or the connection is closed |
| 33 | + group.addTask { try await serviceGroup.run() } |
| 34 | + |
| 35 | + // Set a value for a key. |
| 36 | + let setValue = "bar" |
| 37 | + try await memcacheConnection.set("foo", value: setValue) |
| 38 | + |
| 39 | + // Get the value for a key. |
| 40 | + // Specify the expected type for the value returned from Memcache. |
| 41 | + let getValue: String? = try await memcacheConnection.get("foo") |
| 42 | + |
| 43 | + // Assert that the get operation was successful by comparing the value set and the value returned from Memcache. |
| 44 | + // If they are not equal, this will throw an error. |
| 45 | + assert(getValue == setValue, "Value retrieved from Memcache does not match the set value") |
| 46 | + |
| 47 | + // Cancel all tasks in the task group. |
| 48 | + // This also results in the connection to Memcache being closed. |
| 49 | + group.cancelAll() |
| 50 | + } |
| 51 | + } |
| 52 | +} |
| 53 | +``` |
| 54 | + |
| 55 | +## Contributing |
| 56 | + |
| 57 | +### Docker |
| 58 | + |
| 59 | +We provide a Docker environment for this package. This will automatically start a local Memcached server and run the package tests. |
| 60 | + |
| 61 | +```bash |
| 62 | +docker-compose -f docker/docker-compose.yaml run test |
| 63 | +``` |
0 commit comments