BMCS2013 DATA ENGINEERING 1 of 3
PRACTICAL 4.1 Redis
~~~ As the user student ~~~
1. Installing the Redis Server
Reference
1.1. Install Redis
$ sudo apt update
$ sudo apt install redis-server
1.2. Configure Redis
(a) Edit the Redis configuration file
$ sudo nano /etc/redis/redis.conf
Find the supervised directive and set this to systemd to allow
redis to be managed as a service:
(b) Restart the Redis service to reflect the changes you made to the
configuration file:
$ sudo systemctl restart redis-server
BMCS2013 DATA ENGINEERING 2 of 3
2. Redis CLI
2.1. Invoke the Redis CLI
$ redis-cli
2.2. Test the connectivity to the Redis server
127.0.0.1:6379> ping
PONG
2.3. Set a key-value pair
127.0.0.1:6379> set test "It's working!"
OK
2.4. Retrieve the value
127.0.0.1:6379> get test
"It's working!"
2.5. To exit from the Redis CLI
127.0.0.1:6379> exit
3. Using the Python redis Library
~~~ As the user student ~~~
3.1. Install the redis library in your virtual environment
(.de_venv) $ pip install redis
3.2. Create a Jupyter notebook and test the redis library
Reference
import redis
# Create a connection to the Redis server
r = redis.Redis(host='localhost', port=6379,
db=0)
# Set a key-value pair
r.set('mykey', 'myvalue')
BMCS2013 DATA ENGINEERING 3 of 3
# Retrieve the value of the key
value = r.get('mykey')
print(value.decode('utf-8')) # Outputs:
myvalue
# Set multiple key-value pairs
r.mset({"key1": "value1", "key2": "value2"})
# Get multiple values using their keys
values = r.mget(["key1", "key2"])
for val in values:
print(val.decode('utf-8'))
# Delete a key-value pair
r.delete('mykey')
# Check if a key exists
exists = r.exists('mykey')
print(exists) # Outputs: 0
3.3. Saving and Retrieving Objects
3.3.1. Download user_profile.py from the Classroom’s de
folder
3.3.2. Add the following code to your Jupyter Notebook:
import pickle
from user_profile import UserProfile
user_profile = UserProfile(1234, "Hobbes",
"
[email protected]")
pickled_profile = pickle.dumps(user_profile)
r.set(user_profile.user_id, pickled_profile)
search_obj = r.get(1234)
unpickled_obj = pickle.loads(search_obj)
print(unpickled_obj.to_string())