栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot整合redis使用介绍

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot整合redis使用介绍

前言

本文介绍了springboot集成redis需要的一些配置以及常见的redis操作工具类。


提示:以下是本篇文章正文内容,下面案例可供参考

一、redis是什么?

redis是一个高性能、基于内存级别读写的非关系型数据库

二、使用步骤 引入库

    org.springframework.boot
    spring-boot-starter-data-redis


    cn.hutool
    hutool-all


    org.apache.commons
    commons-pool2


    com.alibaba
    fastjson

定义配置类 数据序列化以及反序列化
public class FastJsonRedisSerializer implements RedisSerializer {
    private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
    private Class clazz;

    public FastJsonRedisSerializer(Class clazz) {
        super();
        this.clazz = clazz;
    }

    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (null == t) {
            return new byte[0];
        }
        return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (null == bytes || bytes.length <= 0) {
            return null;
        }
        String str = new String(bytes, DEFAULT_CHARSET);
        //禁用关键字检测
        return JSON.parseObject(str, clazz, Feature.DisableSpecialKeyDetect);
    }
}
属性配置
@Data
@ConfigurationProperties(
        prefix = "spring.myredis"
)
@Component(value = "MyRedisProperties")
public class MyRedisProperties{
    
    private Integer backupdb;
    private int database = 0;
    private String url;
    private String host = "localhost";
    private String username;
    private String password;
    private int port = 6379;
    private boolean ssl;
    private Duration timeout;
    private Duration connectTimeout;
}
主从库配置
@Configuration
@EnableConfigurationProperties
@EnableCaching
public class RedisConfig {
    @Resource
    MyRedisProperties myRedisProperties;

    
    @Bean
    @Primary
    public RedisTemplate redisTemplateMaster(RedisConnectionFactory redisConnectionFactory){
        // 创建redis序列化器
        RedisTemplate redisTemplate = new RedisTemplate<>();
        FastJsonRedisSerializer objectFastJson2JsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
        redisTemplate.setKeySerializer(objectFastJson2JsonRedisSerializer);
        redisTemplate.setValueSerializer(objectFastJson2JsonRedisSerializer);
        redisTemplate.setHashKeySerializer(objectFastJson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(objectFastJson2JsonRedisSerializer);
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }

    
    @Bean
    public RedisTemplate redisTemplateSlave(RedisConnectionFactory connectionFactory){
        // 创建redis序列化器
        RedisTemplate redisTemplate = new RedisTemplate<>();
        FastJsonRedisSerializer objectFastJson2JsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
        redisTemplate.setKeySerializer(objectFastJson2JsonRedisSerializer);
        redisTemplate.setValueSerializer(objectFastJson2JsonRedisSerializer);
        redisTemplate.setHashKeySerializer(objectFastJson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(objectFastJson2JsonRedisSerializer);
        if(connectionFactory instanceof  LettuceConnectionFactory){
            //创建客户端连接
            LettuceConnectionFactory lettuceConnectionFactory =
                    createLettuceConnectionFactory
                            (myRedisProperties.getBackupdb(),myRedisProperties.getHost(),myRedisProperties.getPort(),myRedisProperties.getPassword(),myRedisProperties.getTimeout().getSeconds()*1000);
            redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        }
        return redisTemplate;
    }

    
    private  LettuceConnectionFactory createLettuceConnectionFactory(
            int dbIndex, String hostName, int port, String password,
            Long timeOut){
        //redis配置
        RedisConfiguration redisConfiguration = new
                RedisStandaloneConfiguration(hostName,port);
        ((RedisStandaloneConfiguration) redisConfiguration).setDatabase(dbIndex);
        ((RedisStandaloneConfiguration) redisConfiguration).setPassword(password);
        //连接池配置
        GenericObjectPoolConfig genericObjectPoolConfig =
                new GenericObjectPoolConfig();
        //redis客户端配置
        LettucePoolingClientConfiguration.LettucePoolingClientConfigurationBuilder
                builder =  LettucePoolingClientConfiguration.builder().
                commandTimeout(Duration.ofMillis(timeOut));
        builder.poolConfig(genericObjectPoolConfig);
        LettuceClientConfiguration lettuceClientConfiguration = builder.build();
        //根据配置和客户端配置创建连接
        LettuceConnectionFactory lettuceConnectionFactory = new
                LettuceConnectionFactory(redisConfiguration,lettuceClientConfiguration);
        lettuceConnectionFactory .afterPropertiesSet();
        return lettuceConnectionFactory;
    }

}
 
常用操作工具类 
public class RedisUtils {
    public RedisTemplate redisTemplate;

    public RedisUtils(Boolean isMaster) {
        if (isMaster) {
            redisTemplate = SpringUtil.getBean("redisTemplateMaster");
            return;
        }
        redisTemplate = SpringUtil.getBean("redisTemplateSlave");
    }

    
    public void setObject(final String key, final Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    
    public  void setObject(final String key, final Object value, final Long timeout, final TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    
    public boolean expire(final String key, final long timeout) {
        return expire(key, timeout, TimeUnit.SECONDS);
    }

    
    public boolean expire(final String key, final long timeout, final TimeUnit unit) {
        return redisTemplate.expire(key, timeout, unit);
    }

    
    public Object getObject(final String key) {
        return redisTemplate.opsForValue().get(key);
    }
    
    public  T getObject(final String key,final Class clazz) {
        return JSONUtil.toBean(JSONUtil.toJsonStr(redisTemplate.opsForValue().get(key)),clazz);
    }

    
    public boolean deleteObject(final String key) {
        return redisTemplate.delete(key);
    }

    
    public long deleteObject(final Collection collection) {
        return redisTemplate.delete(collection);
    }

    
    public long setList(final String key, final Collection dataList) {
        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
        return count == null ? 0 : count;
    }

    
    public List getList(final String key) {
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    
    public  List getList(final String key,final Class clazz) {
        return JSONUtil.toList(JSONUtil.toJsonStr(redisTemplate.opsForList().range(key, 0, -1)),clazz);
    }

    
    public void setSet(final String key, final Set dataSet) {
        redisTemplate.opsForSet().add(key, dataSet);
    }

    
    public Set getSet(final String key) {
        return redisTemplate.opsForSet().members(key);
    }

    
    public void setMap(final String key, final Map dataMap) {
        if (dataMap != null) {
            redisTemplate.opsForHash().putAll(key, dataMap);
        }
    }

    
    public Map getMap(final String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    
    public void setMap(final String key, final String hKey, final Object value) {
        redisTemplate.opsForHash().put(key, hKey, value);
    }

    
    public Object getMap(final String key, final String hKey) {
        return redisTemplate.opsForHash().get(key, hKey);
    }

    
    public List getMap(final String key, final Collection hKeys) {
        return redisTemplate.opsForHash().multiGet(key, hKeys);
    }

    
    public Collection keys(final String pattern) {
        return redisTemplate.keys(pattern);
    }
}
 

启动配置application.yml
spring:
  myredis:
    database: 0
    backupdb: 1
    host: localhost
    port: 6379
    timeout: 30
运行启动类
@SpringBootTest(classes = SpringBootExampleApplication.class)
@Slf4j
@RunWith(SpringRunner.class)
public class RedisTest {
    
    @Test
    public void testRedis(){
        String STRING_KEY = "testString";
        String LIST_KEY = "testList";
        String HASH_KEY = "testHash";
        String SET_KEY = "testSet";
        RedisUtils redisUtils = new RedisUtils(true);
        RedisUtils redisUtilSalve = new RedisUtils(false);

        // string操作
        redisUtils.setObject(STRING_KEY,"test");
        redisUtilSalve.setObject(STRING_KEY,new Student(20,"小明"));
        // list操作
        redisUtils.setList(LIST_KEY, Arrays.asList(1,2));
        redisUtilSalve.setList(LIST_KEY,Arrays.asList(new Student(1,"1"),new Student(2,"2")));
        // map操作
        redisUtils.setMap(HASH_KEY, MapUtil.of(HASH_KEY,"test"));
        redisUtilSalve.setMap(HASH_KEY,MapUtil.of(HASH_KEY,"testSlave"));
        // set 操作
        HashSet hashSet = new HashSet();
        hashSet.add("test");
        hashSet.add("test1");
        redisUtils.setSet(SET_KEY,hashSet);
        hashSet.add("testSalve");
        redisUtilSalve.setSet(SET_KEY,hashSet);

        // 打印展示
        // string打印
        System.out.println(redisUtils.getObject(STRING_KEY));
        Student student = redisUtilSalve.getObject(STRING_KEY, Student.class);
        System.out.println(student);
        // list 打印
        System.out.println(redisUtils.getList(LIST_KEY));
        List studentList = redisUtilSalve.getList(LIST_KEY,Student.class);
        studentList.stream().forEach(System.out::println);
        // map 打印
        redisUtils.getMap(HASH_KEY).forEach((k,v)->{
            System.out.println(k+":"+v);
        });
        redisUtilSalve.getMap(HASH_KEY).forEach((k,v)->{
            System.out.println(k+":"+v);
        });
        // set 打印
        redisUtils.getSet(SET_KEY).forEach(v->{
            System.out.println(v);
        });
        redisUtilSalve.getSet(SET_KEY).forEach(v->{
            System.out.println(v);
        });
    }
}
打印效果
=======string打印======
test
Student(age=20, name=小明)
=======list打印======
[1, 2]
Student(age=1, name=1)
Student(age=2, name=2)
=======map打印======
testHash:test
testHash:testSlave
=======set打印======
[test, test1]
[test, testSalve, test1]
Another Redis Desktop Manager 工具效果


总结

以上就是介绍的全部内容,把一些常用便捷的方法封装进去,方便后续二次开发引用。

源码地址

测试代码地址在:https://gitee.com/teajoy/springboot-modules/tree/master/springboot-example

https://gitee.com/teajoy/springboot-modules/tree/master/springboot-redis

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号