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

2023-07-04 0 1,523

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

首先,我们需要导入Redis的maven依赖

<!-- 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 {
 
    /**
     * 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;
    }
}

然后,我们需要创建一个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;
 
/**
 * @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;
    }
    
}

最后,我们可以使用单元测试来检测我们在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的使用即可。
资源下载此资源下载价格为1小猪币,终身VIP免费,请先
由于本站资源来源于互联网,以研究交流为目的,所有仅供大家参考、学习,不存在任何商业目的与商业用途,如资源存在BUG以及其他任何问题,请自行解决,本站不提供技术服务! 由于资源为虚拟可复制性,下载后不予退积分和退款,谢谢您的支持!如遇到失效或错误的下载链接请联系客服QQ:442469558

:本文采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可, 转载请附上原文出处链接。
1、本站提供的源码不保证资源的完整性以及安全性,不附带任何技术服务!
2、本站提供的模板、软件工具等其他资源,均不包含技术服务,请大家谅解!
3、本站提供的资源仅供下载者参考学习,请勿用于任何商业用途,请24小时内删除!
4、如需商用,请购买正版,由于未及时购买正版发生的侵权行为,与本站无关。
5、本站部分资源存放于百度网盘或其他网盘中,请提前注册好百度网盘账号,下载安装百度网盘客户端或其他网盘客户端进行下载;
6、本站部分资源文件是经压缩后的,请下载后安装解压软件,推荐使用WinRAR和7-Zip解压软件。
7、如果本站提供的资源侵犯到了您的权益,请邮件联系: 442469558@qq.com 进行处理!

猪小侠源码-最新源码下载平台 Java教程 SpringBoot整合Redis实现热点数据缓存的示例代码 http://www.20zxx.cn/775005/xuexijiaocheng/javajc.html

猪小侠源码,优质资源分享网

常见问题
  • 本站所有资源版权均属于原作者所有,均只能用于参考学习,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担
查看详情
  • 最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,建议提前注册好百度网盘账号,使用百度网盘客户端下载
查看详情

相关文章

官方客服团队

为您解决烦忧 - 24小时在线 专业服务