Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Writing in the front

Redis is a NoSql database, often used for caching data, we often need to integrate Redis database access in different system frameworks.

Today we are going to learn how to integrate Redis in the SpringBoot project, and I will attach the usual tool class at the end of the article, let’s learn.

Integrate Redis steps

Add the springboot-redis jar package to the pom.xml file as follows:

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

This introduces the relevant JAR packages that operate redis.

The second step is to initialize the Redis configuration. In SpringBoot, the configuration class is usually used to initialize the related function class.

Let’s create a redisConfiguration.java with the following code:

@Configuration
public class RedisConfiguration {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // Key uses String serialization
        template.setKeySerializer(stringRedisSerializer);
        // The hash key also uses String serialization
        template.setHashKeySerializer(stringRedisSerializer);
        // Value serialization uses Jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // The hash value serialization method uses Jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        returntemplate; }}Copy the code

After initializing the relevant configuration classes, we set the relevant IP and password of Redis in the SpringBoot configuration file.

The application.yml configuration is as follows:

Spring: redis: host: 114.116.243.131 Password: db_jjy_shbdzx port: 6379 timeout: 1000Copy the code

After this operation, we can run normally, but also through redis related classes to redis operation class.

Then we will use the associated utility class to make the call.

The code of the utility class is as follows:

@Component public class RedisUtil { @Autowired private RedisTemplate<String, Object> redisTemplate; /** * public Boolean expire(String key) ** @param time * @param time * @return */ public Boolean expire(String key) long time) { try { if (time > 0) { redisTemplate.expire(key, time, TimeUnit.SECONDS); } return true; } catch (Exception e) { e.printStackTrace(); return false; }} public long getExpire(String key) {return public long getExpire(String key) {return public long getExpire(String key)  redisTemplate.getExpire(key, TimeUnit.SECONDS); } /** * Check whether key exists ** @param key * @return true True False false */ public Boolean hasKey(String key) {try {return redisTemplate.hasKey(key); } catch (Exception e) { e.printStackTrace(); return false; }} /** * delete cache ** @param key can pass a value or multiple */ public void del(String... key) { if (key ! = null && key.length > 0) { if (key.length == 1) { redisTemplate.delete(key[0]); } else { redisTemplate.delete(CollectionUtils.arrayToList(key)); }}} / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = String = = = = = = = = = = = = = = = = = = = = = = = = = = = = = / common cache access to * * * * * * @ @ param key key * / return values public Object get(String key) { return key == null ? null : redisTemplate.opsForValue().get(key); } /** * public Boolean set(String key, String key, String key, String key) Object value) { try { redisTemplate.opsForValue().set(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; }} /** * Normal cache is placed and set to time ** @param key * @param value value * @param time time (s) Time must be greater than 0 if time is equal to or less than 0 will be set indefinitely * @return true success Public Boolean set(String key, Object value, long time) { try { if (time > 0) { redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); } else { set(key, value); } return true; } catch (Exception e) { e.printStackTrace(); return false; }} /** * increment ** @param key * @param delta to increment (> 0) */ public long incr(String key, Long delta) {if (delta < 0) {throw new RuntimeException(" Increment factor must be greater than 0"); } return redisTemplate.opsForValue().increment(key, delta); } /** * decrement ** @param key * @param delta */ public long decr(String key, Long delta) {if (delta < 0) {throw new RuntimeException(" decrement factor must be greater than 0"); } return redisTemplate.opsForValue().increment(key, -delta); }}Copy the code

conclusion

The above is how we integrate and use Redis in the SpringBoot project process, we will introduce the overall springboot-Redis component under the relevant methods, and we learn together.