zram is a driver in linux kernel. It compress the content in memory to reduce the pages used by application.
modprobe zram num_devices=1
# Now you have a /dev/zram0
echo 8G > /sys/block/zram0/disksize
# Must set size before using it
mkfs.ext4 -I 128 -m 0 /dev/zram0
# /dev/zram0 is only a block device therefore we need to create a simple filesystem on it
mount /dev/zram0 /mnt/
# Now you can put some files into /mnt/ and you will find that they will occupied less space.
But that’s not the only way we could use zram. Furthermore, we could use zram with tcmalloc to reduce user application’s cost of memory.
LD_PRELOAD="/usr/lib/libtcmalloc.so" TCMALLOC_MEMFS_MALLOC_PATH=/mnt/ redis-server
Now we make redis-server to use memory in zram. If we use “lsof” to check the redis-server, it will show:
redis-ser 16648 XXX DEL REG 253,0 11 /mnt/.DlM24E redis-ser 16648 XXX 3u REG 253,0 1052672 11 /mnt/.DlM24E (deleted)
That’s the file created by tcmalloc library, and it has already be compressed.