Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Creative Projects for Rust Programmers

You're reading from   Creative Projects for Rust Programmers Build exciting projects on domains such as web apps, WebAssembly, games, and parsing

Arrow left icon
Product type Paperback
Published in Jun 2020
Publisher Packt
ISBN-13 9781789346220
Length 404 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Carlo Milanesi Carlo Milanesi
Author Profile Icon Carlo Milanesi
Carlo Milanesi
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

Preface 1. Rust 2018: Productivity 2. Storing and Retrieving Data FREE CHAPTER 3. Creating a REST Web Service 4. Creating a Full Server-Side Web App 5. Creating a Client-Side WebAssembly App Using Yew 6. Creating a WebAssembly Game Using Quicksilver 7. Creating a Desktop Two-Dimensional Game Using ggez 8. Using a Parser Combinator for Interpreting and Compiling 9. Creating a Computer Emulator Using Nom 10. Creating a Linux Kernel Module 11. The Future of Rust 12. Assessments 13. Other Books You May Enjoy

Storing and retrieving data from a Redis store

Some applications need a very fast response time for certain kinds of data; faster than what a DBMS can offer. Usually, a DBMS dedicated to one user would be fast enough, but for some applications (typically large-scale web applications) there are hundreds of concurrent queries and many concurrent updates. You can use many computers, but the data must be kept coherent among them, and keeping coherence can cause a bottleneck of performance.

A solution to this problem is to use a key-value store, which is a very simple database that can be replicated across a network. This keeps the data in memory to maximize the speed, but it also supports the option to save the data in a file. This avoids losing information if the server is stopped.

A key-value store is similar to the HashMap collection of the Rust standard library, but it is managed by a server process, which could possibly be running on a different computer. A query is a message exchanged between the client and a server. Redis is one of the most used key-value stores.

The source code for this project is found in the redis_example folder. To run it, open the folder and type in cargo run. This will print the following:

a string, 4567, 12345, Err(Response was of incompatible type: "Response type not string compatible." (response was nil)), false.

This simply creates a data store in the current computer and stores in it the following three key-value pairs:

  • "aKey", associated with "a string"
  • "anotherKey", associated with 4567
  • 45, associated with 12345

Then, it queries the store for the following keys:

  • "aKey", which obtains an "a string" value
  • "anotherKey", which obtains a 4567 value
  • 45, which obtains a 12345 value
  • 40, which obtains an error

Then, it queries whether the 40 key exists in the store, which obtains false.

Implementing the project

Only the redis crate is used in this project.

The code is quite short and simple. Let's look at how it works:

fn main() -> redis::RedisResult<()> {
let client = redis::Client::open("redis://localhost/")?;
let mut conn = client.get_connection()?;

First, a client must be obtained. The call to redis::Client::open receives a URL and just checks whether this URL is valid. If the URL is valid, a redis::Client object is returned, which has no open connections. Then, the get_connection method of the client tries to connect, and if it is successful, it returns an open connection.

Any connection essentially has three important methods:

  • set: This tries to store a key-value pair.
  • get: This tries to retrieve the value associated with the specified key.
  • exists: This tries to detect whether the specified key is present in the store, without retrieving its associated value.

Then, set is invoked three times, with different types for the key and value:

conn.set("aKey", "a string")?;
conn.set("anotherKey", 4567)?;
conn.set(45, 12345)?;

At last, get is invoked four times and exists is invoked once. The first three calls get the stored value. The fourth call specifies a non-existent value, so a null value is returned, which cannot be converted into String, as is required, and so an error is generated:

conn.get::<_, String>("aKey")?,
conn.get::<_, u64>("anotherKey")?,
conn.get::<_, u16>(45)?,
conn.get::<_, String>(40),
conn.exists::<_, bool>(40)?);

You can always check the error to find out whether your key is present, but a cleaner solution is to call the exists method, which returns a Boolean value specifying whether the key is present.

With this, we now know how Rust crates are used to access, store, and retrieve data using the most popular databases.

You have been reading a chapter from
Creative Projects for Rust Programmers
Published in: Jun 2020
Publisher: Packt
ISBN-13: 9781789346220
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime