Setting a value message

The first message type we add is SetValue, which provides a pair of key and new value for caching. The struct has two fields—path, which is used as a key, and content, which holds a value:

struct SetValue {
pub path: String,
pub content: Vec<u8>,
}

Let's implement a Message trait for the SetValue struct with an empty unit type if the value is set, and return RedisError if there are issues with a database connection:

impl Message for SetValue {
type Result = Result<(), RedisError>;
}

CacheActor has support for receiving SetValue messages. Let's implement this with the Handler trait:

impl Handler<SetValue> for CacheActor {
type Result = Result<(), RedisError>;

fn handle(&mut self, msg: SetValue, _: &mut Self::Context) -> Self::Result {
self.client.set_ex(msg.path, msg.content, self.expiration)
}
}

We used a Client instance stored in CacheActor to execute the SETEX command from Redis with the set_ex method call. This command sets a value with an expiration period in seconds. As you can see, the implementation is close to the database interaction functions of Chapter 7Reliable Integration with Databases, but implemented as a Handler of the specific message. This code structuring is simpler and more intuitive.