In-depth understanding of Jedis: Common types of data storage used by Java to operate Redis

Table of contents

Preface

1. Introduction to Jedis

1. Jedis’ functions in various aspects

2.Features

2. Java connects to Redis

1. Import pom dependencies

2. Establish a connection

3. Common types of data storage used by Java to operate Redis

1. String

2. Hash table

3. List

4. Collection

5.Ordered collection

4. Examples of practical application scenarios of Redis

1. Meeting information entity

2. Custom annotations

3. Create aspect classes

4. Create the control layer (controller layer)


Preface

As a memory cache database with high performance, multiple data structure support, atomic operations, high availability and scalability, Redis plays a very important role in modern Internet services. Using Redis to manipulate common data types is an essential skill in Java applications. This article will introduce you to how Java operates common data types in Redis, including strings, hash tables, lists, sets and ordered sets.

1. Introduction to Jedis

Jedis is a Redis client written in Java language. It provides relatively comprehensive Redis command operations and can easily use Java code to access and operate the Redis server. The bottom layer of Jedis uses the Java network IO framework Netty and the Java serialization framework Kryo, which has good performance and stability.

1. Jedis’ functions in various aspects

  1. Connection management and connection pooling:

    • Jedis Jedisprovides the function of establishing connection and communication with the Redis server through classes.
    • Jedis has a built-in connection pool function, which can JedisPoolbe managed through classes. Connection pooling can improve performance and reduce the overhead of creating and releasing connections each time.
  2. Data type support:

    • Jedis supports all data types of Redis, including strings, hash tables, lists, sets, ordered sets, etc.
    • For each data type, Jedis provides corresponding methods to perform operations such as adding, getting, updating, and deleting.
  3. Transaction support:

    • Jedis supports transaction operations, and multiple Redis commands can be executed in one transaction.
    • Through Transactionclasses, multiple commands can be added to a transaction and then committed or rolled back together to ensure the atomicity of the operation.
  4. Pipeline support:

    • Jedis supports pipeline operations and can send multiple commands at one time, thereby reducing the number of network round-trips with the Redis server and improving performance.
    • Through Pipelineclasses, multiple commands can be added to the pipeline and sent to the Redis server at once.
  5. Publish-subscribe model supports:

    • Jedis supports the publish-subscribe model of Redis, which can be used to implement functions such as message queues and event notifications.
    • Through JedisPubSubthe class, you can create a subscriber to listen to the specified channel and execute the corresponding callback method when a message is received.
  6. Data serialization and deserialization:

    • Jedis supports custom data serialization and deserialization, and you can RedisSerializercustomize data processing by implementing interfaces.
    • By default, Jedis uses Java's serialization mechanism to serialize and deserialize data, but it also provides other serialization methods, such as JSON, XML, etc.
  7. Advanced feature support:

    • Jedis provides some advanced features, such as distributed locks, Lua script execution, bitmap operations, geographical location-related operations, etc.
    • Distributed locks can implement concurrency control in distributed systems, ensuring that only one thread can access shared resources at the same time.
    • Through JedisClusterclasses, you can easily operate the Redis cluster and read, write and manage data.

2.Features

  1. Easy to use: Jedis provides a simple and easy-to-use API, allowing Java developers to easily interact with Redis without writing complex network communication and protocol parsing code.

  2. High performance: Jedis uses a high-performance communication framework based on Netty, which can quickly respond to requests from the Redis server, and has a built-in connection pool function that can reduce the cost of connection creation and release.

  3. Supports all Redis data types: Jedis supports all Redis data types, including strings, hash tables, lists, sets, ordered sets, etc., and can perform operations such as adding, retrieving, updating, and deleting.

  4. Transaction and pipeline support: Jedis supports transaction and pipeline operations, which can send multiple commands to the Redis server at once, thereby improving performance and ensuring the atomicity of operations.

  5. Publish-subscribe mode support: Jedis supports Redis' publish-subscribe mode, which can be used to implement functions such as message queues and event notifications.

  6. Data serialization support: Jedis supports custom data serialization methods, and you can RedisSerializercustomize data processing by implementing interfaces.

  7. Distributed lock support: Jedis provides the implementation of distributed locks, which can implement concurrency control in distributed systems to ensure that only one thread can access shared resources at the same time.

  8. Advanced feature support: Jedis provides some advanced features, such as Lua script execution, bitmap operations, geographical location-related operations, etc.

  9. Cluster support: Jedis JedisClusterprovides cluster operation functions through classes, which can easily operate Redis clusters.

2. Java connects to Redis

         Both redis and mysq are databases. The process of operating redis in Java is actually similar to that of operating mysql. First, import dependencies and establish connections, but the methods are different. Redis is a non-relational database and mysql is a relational database.

What are relational databases and non-relational databases?

  •         A relational database is a database system based on a relational model, in which data is organized in tabular form and is queried and managed using SQL (Structured Query Language). In a relational database, data consists of multiple tables, each table contains multiple rows and columns, each row represents a record and each column represents an attribute. Relationships can be established between tables in a relational database, and joint queries and updates of data can be achieved through these relationships. The most common examples of relational databases are MySQL, Oracle, and SQL Server.
  •         Compared with traditional relational databases, non-relational databases (NoSQL) use non-relational data models to store and process data. Non-relational databases usually do not use tables, but other forms of data structures such as key-value pairs, documents, graphs, etc. to better handle large amounts of unstructured data. NoSQL databases generally have high scalability, flexibility, and performance, and are capable of handling complex data processing tasks. The most common examples of non-relational databases are MongoDB, Cassandra, and Redis.

1. Import pom dependencies

Import the redis pom dependency in the maven project

    <!--redis-->
    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>2.9.0</version>
    </dependency>

2. Establish a connection

Let’s start our Redis first

package com.ctb.ssm.redis;

import redis.clients.jedis.Jedis;

/**
 * @author 彪
 * @remark
 * @create  2023-11-06 10:30
 */
public class Demo1 {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("localhost", 6379);//主机地址,端口号
        jedis.auth("123456");//密码
        System.out.println(jedis.ping());

    }
}

The connection is successful 

3. Common types of data storage used by Java to operate Redis

1. String

String is the simplest data type in Redis and one of the most common data types.

package com.ctb.ssm.redis;

// 导入Jedis库
import redis.clients.jedis.Jedis;

public class StringExample {
    public static void main(String[] args) {
        // 创建Jedis对象,连接Redis服务器
        Jedis jedis = new Jedis("localhost");

        // 存储字符串数据
        jedis.set("name", "John Doe");

        // 获取字符串数据
        String name = jedis.get("name");
        System.out.println("Name: " + name);

        // 更新字符串数据
        jedis.set("name", "Jane Doe");
        name = jedis.get("name");
        System.out.println("Updated Name: " + name);

        // 删除字符串数据
        jedis.del("name");
        name = jedis.get("name");
        System.out.println("Deleted Name: " + name);

        // 关闭连接
        jedis.close();
    }
}

2. Hash table

Hash table is a key-value type data structure in Redis, which is similar to Map in Java.

// 导入Jedis库
import redis.clients.jedis.Jedis;

package com.ctb.ssm.redis;

import java.util.HashMap;
import java.util.Map;

public class HashExample {
    public static void main(String[] args) {
        // 创建Jedis对象,连接Redis服务器
        Jedis jedis = new Jedis("localhost");

        // 存储哈希表数据
        Map<String, String> user = new HashMap<>();
        user.put("name", "John Doe");
        user.put("age", "30");
        user.put("email", "[email protected]");
        jedis.hset("user:1", user);

        // 获取哈希表数据
        Map<String, String> storedUser = jedis.hgetAll("user:1");
        System.out.println("Name: " + storedUser.get("name"));
        System.out.println("Age: " + storedUser.get("age"));
        System.out.println("Email: " + storedUser.get("email"));

        // 更新哈希表数据
        jedis.hset("user:1", "age", "31");
        storedUser = jedis.hgetAll("user:1");
        System.out.println("Updated Age: " + storedUser.get("age"));

        // 删除哈希表数据
        jedis.hdel("user:1", "email");
        storedUser = jedis.hgetAll("user:1");
        System.out.println("Deleted Email: " + storedUser.get("email"));

        // 关闭连接
        jedis.close();
    }
}

3. List

A list is an ordered data structure in Redis that can store multiple elements of string type.

package com.ctb.ssm.redis;

// 导入Jedis库
import redis.clients.jedis.Jedis;

import java.util.List;

public class ListExample {
    public static void main(String[] args) {
        // 创建Jedis对象,连接Redis服务器
        Jedis jedis = new Jedis("localhost");

        // 存储列表数据
        jedis.lpush("fruits", "apple");
        jedis.lpush("fruits", "banana");
        jedis.lpush("fruits", "orange");

        // 获取列表数据
        List<String> fruits = jedis.lrange("fruits", 0, -1);
        for (String fruit : fruits) {
            System.out.println("Fruit: " + fruit);
        }

        // 弹出列表元素
        String poppedFruit = jedis.lpop("fruits");
        System.out.println("Popped Fruit: " + poppedFruit);

        // 关闭连接
        jedis.close();
    }
}

4. Collection

A set is an unordered data structure in Redis that can store multiple string type elements, and each element is unique.

package com.ctb.ssm.redis;

// 导入Jedis库
import redis.clients.jedis.Jedis;

import java.util.Set;

public class SetExample {
    public static void main(String[] args) {
        // 创建Jedis对象,连接Redis服务器
        Jedis jedis = new Jedis("localhost");

        // 存储集合数据
        jedis.sadd("tags", "java");
        jedis.sadd("tags", "python");
        jedis.sadd("tags", "javascript");

        // 获取集合数据
        Set<String> tags = jedis.smembers("tags");
        for (String tag : tags) {
            System.out.println("Tag: " + tag);
        }

        // 判断元素是否存在于集合中
        boolean exists = jedis.sismember("tags", "python");
        System.out.println("Python exists in tags set: " + exists);

        // 删除集合元素
        jedis.srem("tags", "python");
        exists = jedis.sismember("tags", "python");
        System.out.println("Python exists in tags set after removal: " + exists);

        // 关闭连接
        jedis.close();
    }
}

5.Ordered collection

An ordered set is an ordered data structure in Redis. It can store multiple string type elements. Each element has a corresponding score and can be sorted according to the score.

package com.ctb.ssm.redis;

// 导入Jedis库
import redis.clients.jedis.Jedis;

import java.util.Set;

public class SortedSetExample {
    public static void main(String[] args) {
        // 创建Jedis对象,连接Redis服务器
        Jedis jedis = new Jedis("localhost");

        // 存储有序集合数据
        jedis.zadd("scores", 90, "Alice");
        jedis.zadd("scores", 80, "Bob");
        jedis.zadd("scores", 95, "Charlie");

        // 获取有序集合数据
        Set<String> topScorers = jedis.zrevrange("scores", 0, 2);
        for (String scorer : topScorers) {
            System.out.println("Top Scorer: " + scorer);
        }

        // 更新有序集合数据
        jedis.zincrby("scores", 5, "Alice");
        double aliceScore = jedis.zscore("scores", "Alice");
        System.out.println("Updated Alice Score: " + aliceScore);

        // 关闭连接
        jedis.close();
    }
}

4. Examples of practical application scenarios of Redis

Redis is generally used to store data that basically does not change: such as meeting status, etc. The values ​​stored in the database need to be translated into the corresponding status, such as pending meetings, historical meetings, etc.

We can use Redis to perform a storage, and then find the corresponding content based on the corresponding value.

1. Meeting information entity

package com.ctb.ssm.model;

public class Meeting {
    private String id;
    private String name;
    private int state;

    // 构造方法、getter和setter省略
}

Among them, the state field is represented by int type, 1 represents the meeting to be held, 2 represents the historical meeting, and 3 represents the released meeting.

2. Custom annotations

package com.ctb.ssm.annotation;

import java.lang.annotation.*;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface State {
    String value();
    int code();
}

In the annotation, the conference status name is obtained through the value() method, and the conference status value is obtained through the code() method.

3. Create aspect classes

Used to traverse the meeting list when querying meeting information, and perform special processing based on the value of the status field

package com.ctb.ssm.Aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Aspect
@Component
public class MeetingAspect {

    private JedisPool jedisPool;

    public MeetingAspect() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPool = new JedisPool(jedisPoolConfig, "localhost", 6379);
    }

    @Around("execution(* com.example.MeetingService.getMeetings())")
    public Object processMeetings(ProceedingJoinPoint joinPoint) throws Throwable {
        Jedis jedis = jedisPool.getResource();

        try {
            List<Meeting> meetings = (List<Meeting>) joinPoint.proceed();

            for (Meeting meeting : meetings) {
                int stateCode = meeting.getState();
                // 根据stateCode将会议状态存储到Redis中
                jedis.hset("meeting_states", String.valueOf(stateCode), getStateNameByCode(stateCode));
            }

            return meetings;
        } finally {
            jedis.close();
        }
    }

    private String getStateNameByCode(int stateCode) {
        switch (stateCode) {
            case 1:
                return "待开会议";
            case 2:
                return "历史会议";
            case 3:
                return "发布会议";
            default:
                return "取消会议";
        }
    }
}

We created a JedisPool and initialized it to obtain a Jedis instance to operate Redis. In the processMeetings method, we can obtain the queried meeting list meetings and traverse each Meeting object. According to the status field of the meeting object state, we can jedis.hset()store the corresponding meeting status name into the Redis hash table "meeting_states" by calling the method.

4. Create the control layer (controller layer)

@RestController
public class MeetingController {

    @Autowired
    private MeetingService meetingService;

    @GetMapping("/meetings")
    public List<Meeting> getMeetings() {
        List<Meeting> meetings = meetingService.getMeetings();
        return meetings;
    }
}

We defined an interface "/meetings" in MeetingController to obtain all meeting information. In this interface, we call the getMeetings method of MeetingService to obtain all meeting information and return it directly to the front end.

Guess you like

Origin blog.csdn.net/weixin_74268571/article/details/134241226