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

009

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

009

009_Redis_RedisTemplate入门

1、创建一个springboot项目
springboot注入依赖优点慢呀!困了,有好心人知道创建springboot怎么样才能使导入依赖快一点呀!!!!!!求告知!

写一下配置文件。

spring:
  redis:
    host: 10.223.31.215
    port: 6379
    lettuce:
      pool:
        max-active: 8
        max-idle: 8
        min-idle: 0
        max-wait: 100ms

编写测试类

package com.ym.redisdemo;

import lombok.val;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;

@SpringBootTest
class RedisDemoApplicationTests {

    //注入Redis
    @Autowired
    private RedisTemplate redisTemplate;
    @Test
    void contextLoads() {
        //写入一条String数据
        redisTemplate.opsForValue().set("name","李易峰");
        //获取String数据
        Object name = redisTemplate.opsForValue().get("name");
        System.out.println("name="+name);
    }

}

单元测试

2、SpringDataRedis的使用步骤

  • 引入依赖
  • 配置redis地址信息
  • 本地注入RedisTemplate

3、在客户端工具查询刚刚插入的String数据

数据在存储的时候被序列化了,默认JDK序列化方式被存储。

4、SpringDataRedis的序列化方式

RedisTemplate可以接受任意Object作为值写入Redis,只不过写入之前会把Object对象序列化成字节的形式,默认采用的是JDK序列化,也就是上图我们看到的结果。其存在的缺点如下。

  • 可读性差
  • 内存占用较大

5、序列化操作

package com.ym.redisdemo.com.ym.redis.config;

import lombok.val;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;


@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory){
        //创建对象
        RedisTemplate template = new RedisTemplate();
        //设置连接工厂
        template.setConnectionFactory(connectionFactory);
        //设置key的序列化
        GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer=new GenericJackson2JsonRedisSerializer();
        template.setKeySerializer(RedisSerializer.string());
        template.setHashKeySerializer(RedisSerializer.string());
        //设置value的序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashKeySerializer(jackson2JsonRedisSerializer);
        //返回
        return template;
    }
}


测试对象

    @Test
    void testSaveUser(){
        //写入数据
        redisTemplate.opsForValue().set("user:100",new User("李易峰",18));
        User o = (User) redisTemplate.opsForValue().get("user:100");
        System.out.println(o);
    }

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

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

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