SpringBoot整合Redis实现热点数据缓存的示例代码

2023-03-13 14:03:23 示例 缓存 热点

我们以IDEA + SpringBoot作为 Java中整合Redis的使用 的测试环境

首先,我们需要导入RedisMaven依赖

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

其次,我们需要在配置文件中配置你的Redis配置信息,我使用的是 .yml文件格式 

# 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

对 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 {
 
    
    @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;
    }
 
    
    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;
    }
}

然后,我们需要创建一个RedisUtil来对Redis数据库进行操作

package com.zyxx.test.utils;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
 

@Component
public class RedisUtil {
 
    @Autowired
    private RedisTemplate<String, String> template;
 
    
    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;
    }
 
    
    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;
    }
 
    
    public boolean del(final String key) {
        boolean res = false;
        try {
            template.delete(key);
            res = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }
    
	
    public boolean hasKey(final String key) {
        boolean res = false;
        try {
            res = template.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }
 
	
    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;
    }
 
    
    public long getExpire(final String key) {
        long res = 0;
        try {
            res = template.getExpire(key, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }
 
	
    public boolean persist(final String key) {
        boolean res = false;
        try {
            res = template.persist(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }
    
}

最后,我们可以使用单元测试来检测我们在RedisUtil中写的操作Redis数据库的方法

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);
    }
    
}
  • 推荐使用Redis客户端(redis-desktop-manager)来查看Redis数据库中的数据
  • 至此,我们在日常项目中整合Redis的基本使用操作就完成了,但在实际项目中,可能会涉及到更复杂的用法,可以根据你的业务需求调整Redis的使用即可。

到此这篇关于SpringBoot中整合Redis实现热点数据缓存的文章就介绍到这了,更多相关SpringBoot热点数据缓存内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关文章