Springboot integrates and uses redis common functions

The pure redis command line operation may be the same as the pure mysql command line operation, and there will be a feeling that it is used for use. So generally speaking, as a cache middleware, redis will be supplemented by other client languages, such as java.
Redis is open source, and java is also open source. This is destined to have more than one client connection to redis in java. Common ones are jedis, redisson, and lettuce.
In today's social environment where everything is running at high speed, java software development is also extremely pursuing code output efficiency, so springcloud and springboot are everywhere.
The idea that springboot convention is better than configuration, to a certain extent also greatly simplifies the development work, so when learning redis integration and use in java, I also chose to use springboot.

springboot integrated redis

The integration of redis in springboot is similar to the integration of other components in springboot. Basically, a starter can be introduced:

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

Data source connection configuration

With the introduction of dependencies, the next step is to configure redis. If the yml format is used in springboot, the basic configuration is as follows:

spring:
    redis:
        host: 192.168.139.9
        password:
        database: 0
        port: 6379

The above host points to the ip of the Redis server. Here is the ip of my own virtual machine. No password is set, so there is no password.
Redis has 16 databases by default, which can be modified in the configuration file. I didn't modify it, and I still use the default 16 databases. Here, the client connection uses database 0. Similarly, the port number uses the default 6379.

restTemplate use

Most of the operations of redis in springboot are unified encapsulated, namely RedisTemplate. For the five basic data types of redis mentioned before and some common advanced functions, all operations are performed through RedisTemplate.

redisTemplate.opsForValue() can get an operation on string type;
redisTemplate.opsForList() can get an operation on list type;
redisTemplate.opsForHash() can get an operation on hash type;
redisTemplate.opsForSet() can get one Operation on set type;
redisTemplate.opsForZSet() can get an operation on sorted_set type

Based on the above content, we can demonstrate the basic storage operations of five types of data, for example:

redisTemplate.opsForValue().set(key,value);
redisTemplate.opsForList().leftPush(key,value);
redisTemplate.opsForHash().put(key,key,value);
redisTemplate.opsForSet().add(key,value);
redisTemplate.opsForZSet().add(key,value,0);

According to the basic data types, there are actually many types in string, such as bitmap. The version of springboot-redis I am currently using does not seem to fully support all operations of bitmap. For example, there is a ready-made package for saving bitmap, which can be written as follows:

redisTemplate.opsForValue().setBit(key,0,true);

But like bitmap's statistical bitcount, there is no direct operation method, you need to write your own callback function to operate:

redisTemplate.execute((RedisCallback<Long>)connection -> connection.bitCount((key).getBytes()));

In addition to simple operations of basic data types, redisTemplte can also perform expiration settings, and operations of advanced functions such as pipelines, such as;

redisTemplate.expire("k111",200, TimeUnit.SECONDS);
redisTemplate.expireAt("k111",new Date());

redisTemplate.executePipelined(new RedisCallback<Object>() {
    @Override
    public Object doInRedis(RedisConnection connection) throws DataAccessException {
        connection.openPipeline();
        connection.set("k111".getBytes(),"t111".getBytes());
        connection.set("k222".getBytes(),"t222".getBytes());
        return null;
    }
});

The expiration operation is actually very simple. Like some other operations, it is very similar to the command line operation. Basically, you can understand the usage by clicking the api prompt. The pipeline operation is relatively complicated, and you need to implement a certain callback function for processing. , But it is actually relatively simple.

Simple configuration of connection pool

When actually using redis, it will not just configure ip and port as above, but will add other configurations, such as connection pool.
As mentioned above, there are three commonly used clients to connect to redis in java. Springboot uses lettuce by default, so the default connection pool configuration also uses lettuce. After adding a few simple configurations of the connection pool, the redis configuration is as follows:

spring:
    redis:
        host: 192.168.139.9
        password:
        database: 0
        port: 6379
        lettuce:
            shutdown-timeout: 100ms
            pool:
                maxIdle: 5
                maxActive: 20

It should be noted here that although the lettuce connection pool can be configured, it actually lacks dependencies. If you start it like this, you will find that it will report an error at startup:

Caused by: java.lang.NoClassDefFoundError: org/apache/commons/pool2/impl/GenericObjectPoolConfig
	at org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration$LettucePoolingClientConfigurationBuilder.<init>(LettucePoolingClientConfiguration.java:94) ~[spring-data-redis-2.3.1.RELEASE.jar:2.3.1.RELEASE]
	at org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration.builder(LettucePoolingClientConfiguration.java:51) ~[spring-data-redis-2.3.1.RELEASE.jar:2.3.1.RELEASE]

The above error message is actually very obvious, it is the lack of commons-pool2 related classes, so we need to introduce related dependencies here;

<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-pool2</artifactId>
</dependency>

After having the above dependency, start it again and it can be used normally.

Key display is not normal

The above operation looks fine, but there is actually a problem. If you take a look at the data, you will find that the key of the data is not the content we saved in, and some of it will look like garbled codes.
One of the solutions is to use the high-level API encapsulated by springboot, namely StringRedisTemplate, and the other is to configure redis serialization, for example:

  @Autowired(required = false)
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);
        this.redisTemplate = redisTemplate;
    }

related articles

Caching and redis related basic knowledge
Linux redis installation and software installation related Linux knowledge points
redis data type key knowledge and application scenarios
redis pipeline, transaction, publish and subscribe, expiration, filter and other common advanced functions (part 1)
redis pipeline, A small note of commonly used advanced functions such as transactions, publish and subscribe, expiration, filters, etc. (Part 2)
Springboot integration and use of redis common functions

Guess you like

Origin blog.csdn.net/tuzongxun/article/details/107794207