Home  >  Article  >  Database  >  How SpringBoot integrates Redis to implement hotspot data caching

How SpringBoot integrates Redis to implement hotspot data caching

王林
王林forward
2023-05-27 14:07:111623browse

We use IDEA SpringBoot as the test environment for integrating Redis in Java

First, we need to import the maven dependency of Redis

<!-- Redis的maven依赖包 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>

Secondly, we need to Configure your Redis configuration information in the configuration file. I use the .yml file format

# redis配置
spring:
  redis:
    # r服务器地址
    host: 127.0.0.1
    # 服务器端口
    port: 6379
    # 数据库索引(默认0)
    database: 0
    # 连接超时时间(毫秒)
    timeout: 10s
    jedis:
      pool:
        # 连接池中的最大空闲连接数
        max-idle: 8
        # 连接池中的最小空闲连接数
        min-idle: 0
        # 连接池最大连接数(使用负值表示没有限制)
        max-active: 8
        # 连接池最大阻塞等待时间(使用负值表示没有限制)
        max-wait: -1

Make custom configurations for redis

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
 
@Configuration
public class RedisConfigurer extends CachingConfigurerSupport {
 
    /**
     * redisTemplate 序列化使用的jdkSerializeable, 存储二进制字节码, 所以自定义序列化类
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
        // 配置redisTemplate
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        // 设置序列化
        Jackson2JsonRedisSerializer<Object> redisSerializer = getRedisSerializer();
        // key序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // value序列化
        redisTemplate.setValueSerializer(redisSerializer);
        // Hash key序列化
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        // Hash value序列化
        redisTemplate.setHashValueSerializer(redisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
 
    /**
     * 设置Jackson序列化
     */
    private Jackson2JsonRedisSerializer<Object> getRedisSerializer() {
        Jackson2JsonRedisSerializer<Object> redisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        redisSerializer.setObjectMapper(om);
        return redisSerializer;
    }
}

Then, we need to create a RedisUtil to configure the Redis database Operation

package com.zyxx.test.utils;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
 
/**
 * @ClassName RedisUtil
 * @Author 
 * @Date 2019-08-03 17:29:29
 * @Version 1.0
 **/
@Component
public class RedisUtil {
 
    @Autowired
    private RedisTemplate<String, String> template;
 
    /**
     * 读取数据
     *
     * @param key
     * @return
     */
    public String get(final String key) {
        return template.opsForValue().get(key);
    }
 
    /**
     * 写入数据
     */
    public boolean set(final String key, String value) {
        boolean res = false;
        try {
            template.opsForValue().set(key, value);
            res = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }
 
    /**
     * 根据key更新数据
     */
    public boolean update(final String key, String value) {
        boolean res = false;
        try {
            template.opsForValue().getAndSet(key, value);
            res = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }
 
    /**
     * 根据key删除数据
     */
    public boolean del(final String key) {
        boolean res = false;
        try {
            template.delete(key);
            res = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }
    
	/**
     * 是否存在key
     */
    public boolean hasKey(final String key) {
        boolean res = false;
        try {
            res = template.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }
 
	/**
     * 给指定的key设置存活时间
     * 默认为-1,表示永久不失效
     */
    public boolean setExpire(final String key, long seconds) {
        boolean res = false;
        try {
            if (0 < seconds) {
                res = template.expire(key, seconds, TimeUnit.SECONDS);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }
 
    /**
     * 获取指定key的剩余存活时间
     * 默认为-1,表示永久不失效,-2表示该key不存在
     */
    public long getExpire(final String key) {
        long res = 0;
        try {
            res = template.getExpire(key, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }
 
	/**
     * 移除指定key的有效时间
     * 当key的有效时间为-1即永久不失效和当key不存在时返回false,否则返回true
     */
    public boolean persist(final String key) {
        boolean res = false;
        try {
            res = template.persist(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }
    
}

Finally, we can use unit testing to detect the method we wrote in RedisUtil to operate the Redis database

package com.zyxx.test;
 
import com.zyxx.test.utils.RedisUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
 
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestApplicationTest {
 
    @Resource
    private RedisUtil redisUtil;
 
    @Test
    public void setRedis() {
        boolean res = redisUtil.set("jay", "周杰伦 - 《以父之名》");
        System.out.println(res);
    }
 
    @Test
    public void getRedis() {
        String res = redisUtil.get("jay");
        System.out.println(res);
    }
 
 
    @Test
    public void updateRedis() {
        boolean res = redisUtil.update("jay", "周杰伦 - 《夜的第七章》");
        System.out.println(res);
    }
 
    @Test
    public void delRedis() {
        boolean res = redisUtil.del("jay");
        System.out.println(res);
    }
 
	@Test
    public void hasKey() {
        boolean res = redisUtil.hasKey("jay");
        System.out.println(res);
    }
 
	@Test
    public void expire() {
        boolean res = redisUtil.setExpire("jay", 100);
        System.out.println(res);
    }
 
    @Test
    public void getExpire() {
        long res = redisUtil.getExpire("jay");
        System.out.println(res);
    }
 
	@Test
    public void persist() {
        boolean res = redisUtil.persist("jay");
        System.out.println(res);
    }
    
}
  • It is recommended to use redis-desktop-manager as Redis Display tool for data in the database

  • At this point, we have completed the basic usage of integrating Redis in daily projects, but in actual projects, more complex usage may be involved. You can adjust the use of Redis according to your business needs.

The above is the detailed content of How SpringBoot integrates Redis to implement hotspot data caching. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete