Home Database Redis What is the difference between redis and jedis

What is the difference between redis and jedis

Jun 29, 2019 pm 05:10 PM

What is the difference between redis and jedis

The integration of redis and spring is generally divided into spring-data-redis integration and jedis integration. Let’s first look at the difference between the two.

1. The referenced dependencies are different:

The dependencies used by spring-data-redis are as follows:

<dependency>  
      <groupId>org.springframework.data</groupId>  
      <artifactId>spring-data-redis</artifactId>  
      <version>1.8.9.RELEASE</version>  
</dependency>
Copy after login

The dependencies used by jedis are as follows:

<dependency>
       <groupId>redis.clients</groupId>
       <artifactId>jedis</artifactId>
       <version>2.9.0</version>
       <type>jar</type>
       <scope>compile</scope>
</dependency>
Copy after login

2. Differences in how to manage jedis instances and operate redis services:

spring-data-redis:

It is managed through org.springframework.data.redis.connection.jedis.JedisConnectionFactory, that is, through factory class management, and then operates the redis service through the configured template bean. , the code segment is filled with a large number of template fragment codes that have nothing to do with the business. The code is redundant and difficult to maintain. For example, the following code:

protected RedisTemplate<Serializable, Serializable> redisTemplate;
 
public void saveUser(User user) {
    redisTemplate.execute(new RedisCallback<Object>() {
 
 
        @Override
        public Object doInRedis(RedisConnection connection) throws DataAccessException {
            connection.set(redisTemplate.getStringSerializer().serialize("user.uid." + user.getId()),
                           redisTemplate.getStringSerializer().serialize(user.getName()));
            return null;
        }
    });
}
 
 
public User getUser(long id) {
    return redisTemplate.execute(new RedisCallback<User>() {
        @Override
        public User doInRedis(RedisConnection connection) throws DataAccessException {
            byte[] key = redisTemplate.getStringSerializer().serialize("user.uid." + id);
            if (connection.exists(key)) {
                byte[] value = connection.get(key);
                String name = redisTemplate.getStringSerializer().deserialize(value);
                User user = new User();
                user.setName(name);
                user.setId(id);
                return user;
            }
            return null;
        }
    });
}
Copy after login

Introduction to RedisTemplate

spring encapsulates the RedisTemplate object for comparison Various operations of redis, it supports all redis native APIs. RedisTemplate provides the use of several commonly used interface methods, namely:

private ValueOperations valueOps; private ListOperations listOps;private SetOperations setOps; private ZSetOperations zSetOps;

RedisTemplate defines five data structure operations

redisTemplate.opsForValue();//操作字符串
redisTemplate.opsForHash();//操作hash
redisTemplate.opsForList();//操作list
redisTemplate.opsForSet();//操作set
redisTemplate.opsForZSet();//操作有序set
StringRedisTemplate与RedisTemplate
Copy after login

The relationship between the two is that StringRedisTemplate inherits RedisTemplate.
The data between the two is not common; that is to say, StringRedisTemplate can only manage the data in StringRedisTemplate, and RedisTemplate can only manage the data in RedisTemplate.
There are two serialization strategies adopted by SDR by default, one is the serialization strategy of String and the other is the serialization strategy of JDK.
StringRedisTemplate uses the String serialization strategy by default, and the saved keys and values ​​are serialized and saved using this strategy.

RedisTemplate uses the JDK serialization strategy by default, and the saved keys and values ​​are serialized and saved using this strategy.

jedis method:

Managed through redis.clients.jedis.JedisPool, that is, managed through the pool, obtain the jedis instance through the pool object, and then directly operate the redis service through the jedis instance, eliminating Redundant code that has nothing to do with the business, such as the following code snippet:

private JedisPool jedisPool;
public String save(String key,String val) {
Jedis jedis = jedisPool.getResource();
return jedis.set(key, val);
}
Copy after login

The change from factory class to pool is equivalent to the change in the way mybatis connects to mysql. The code becomes simpler and easier to maintain. It's easier. Jedis uses apache commons-pool2 to manage the Jedis resource pool, so a very important parameter when defining JedisPool is the resource pool GenericObjectPoolConfig. The usage method is as follows, which has many parameters for resource management and use.

Parameter description

JedisPool ensures that resources are within a controllable range and provides thread safety, but a reasonable GenericObjectPoolConfig configuration can protect applications using Redis. Here are some of its details Important parameters are explained and suggested:

In the current environment, the Jedis connection is the resource, and the JedisPool manages the Jedis connection.

1. Resource settings and usage

maxTotal: the maximum number of connections in the resource pool; default value: 8 See the next section for setting suggestions
maxIdle: the maximum number of idle connections allowed in the resource pool; Default value: 8; Usage recommendations: See the next section for setting recommendations
minIdle: The resource pool ensures the minimum number of idle connections; Default value: 0; Usage recommendations: See the next section for setting recommendations
blockWhenExhausted: When the resource pool is exhausted After that, whether the caller wants to wait. Only when true, the following maxWaitMillis will take effect; Default value: true; Usage recommendations: It is recommended to use the default value
maxWaitMillis: When the resource pool connection is exhausted, the caller's maximum waiting time (in milliseconds) - 1: Indicates never timeout; Usage recommendations: It is not recommended to use the default value
testOnBorrow: Whether to perform connection validity detection (ping) when borrowing a connection from the resource pool, invalid connections will be removed; Default value: false; Usage recommendations : When the business volume is large, it is recommended to set it to false (the cost of one more ping).
testOnReturn: Whether to perform connection validity detection (ping) when returning the connection to the resource pool, invalid connections will be removed; Default value: false; Usage recommendations: When the business volume is large, it is recommended to set it to false (one more ping overhead).
jmxEnabled: Whether to enable jmx monitoring, which can be used for monitoring; Default value: true; Usage recommendations: It is recommended to enable it, but the application itself must also be enabled

2. Idle resource monitoring

Idle Jedis Object detection is completed by a combination of the following four parameters. testWhileIdle is the switch of this function.

testWhileIdle: Whether to enable idle resource monitoring; Default value: false; Usage suggestions: true
timeBetweenEvictionRunsMillis: Detection period of idle resources (unit: milliseconds); Default value: -1: No detection; Usage suggestions: Recommended settings , choose the period by yourself, you can also use the default or use the configuration in JedisPoolConfig below
minEvictableIdleTimeMillis: the minimum idle time of resources in the resource pool (unit: milliseconds), after reaching this value, idle resources will be removed; default value: 1000 60 30 = 30 minutes; Usage suggestions: You can decide according to your own business. Most of the default values ​​are sufficient. You can also consider using the configuration in JeidsPoolConfig below
numTestsPerEvictionRun: The number of samples per time when detecting idle resources; default value: 3; Usage suggestions: You can fine-tune according to the number of your own application connections. If set to -1, all connections will be monitored for idleness

For more Redis related knowledge, please visit Redis usage tutorial Column!

The above is the detailed content of What is the difference between redis and jedis. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to build the redis cluster mode How to build the redis cluster mode Apr 10, 2025 pm 10:15 PM

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

How to clear redis data How to clear redis data Apr 10, 2025 pm 10:06 PM

How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

How to use the redis command How to use the redis command Apr 10, 2025 pm 08:45 PM

Using the Redis directive requires the following steps: Open the Redis client. Enter the command (verb key value). Provides the required parameters (varies from instruction to instruction). Press Enter to execute the command. Redis returns a response indicating the result of the operation (usually OK or -ERR).

How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

How to use redis lock How to use redis lock Apr 10, 2025 pm 08:39 PM

Using Redis to lock operations requires obtaining the lock through the SETNX command, and then using the EXPIRE command to set the expiration time. The specific steps are: (1) Use the SETNX command to try to set a key-value pair; (2) Use the EXPIRE command to set the expiration time for the lock; (3) Use the DEL command to delete the lock when the lock is no longer needed.

How to use the redis command line How to use the redis command line Apr 10, 2025 pm 10:18 PM

Use the Redis command line tool (redis-cli) to manage and operate Redis through the following steps: Connect to the server, specify the address and port. Send commands to the server using the command name and parameters. Use the HELP command to view help information for a specific command. Use the QUIT command to exit the command line tool.

How to make message middleware for redis How to make message middleware for redis Apr 10, 2025 pm 07:51 PM

Redis, as a message middleware, supports production-consumption models, can persist messages and ensure reliable delivery. Using Redis as the message middleware enables low latency, reliable and scalable messaging.

See all articles