SpringBoot 学习(九)Redis

news/2024/7/23 11:06:13 标签: spring boot, 学习, redis

11. 集成 Redis

11.1 说明

  • SpringBoot 操作数据:sping-data、jpa、jdbc、mongodb、redis

  • SpringBoot 2.× 后,jedis 被替换为 lettuce

    jedis:采用直连,多线程操作不安全,增强安全性需使用 jedis pool 连接池!更像 BIO 模式。

    lettuce:采用 netty,实例可在多个线程中共享,不存在线程不安全的情况!更像 NIO 模式。

11.2 源码分析

@Bean
@ConditionalOnMissingBean(name = "redisTemplate")
@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
   // 默认的 RedisTemplate 没有过多的设置,redis 对象都需要序列化
   // 两个泛型都是 Object,需要强制转换为 <String, Object>
   RedisTemplate<Object, Object> template = new RedisTemplate<>();
   template.setConnectionFactory(redisConnectionFactory);
   return template;
}

@Bean
@ConditionalOnMissingBean
@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
// 由于 String 是常用类型所以单独提出一个 bean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
   StringRedisTemplate template = new StringRedisTemplate();
   template.setConnectionFactory(redisConnectionFactory);
   return template;
}

11.3 测试

(1) 导入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

redis_48">(2) 配置 redis

# application.properties
spring.redis.host=127.0.0.1
spring.redis.port=6379

(3) 测试

● 传输字符串
@SpringBootTest
class RedisApplicationTests {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    void contextLoads() {

        /**
         * redisTemplate 可操作不同的数据类型,可完成基本的操作,如 CRUD
         * opsForValue 字符串
         * opsForList
         * opsForSet
         * opsForHash
         * opsForZSet
         * opsForGeo
         * opsForHyperLogLog
         *
         * 获取 redis 连接对象
         * RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
         * connection.flushDb();
         * connection.flushAll() ;
         */

        redisTemplate.opsForValue().set("myKey", "why");
        System.out.println("myKey: " + redisTemplate.opsForValue().get("myKey"));
    }
}

在这里插入图片描述

在这里插入图片描述

● 传输对象
// 实体类
@Component
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String name;
    private String password;
}
@Test
void test() throws JsonProcessingException {
    User user = new User("why", "123");
    redisTemplate.opsForValue().set("user", user);
    System.out.println(redisTemplate.opsForValue().get("user"));
}

在这里插入图片描述

● 传输 JSON
@Test
void test() throws JsonProcessingException {
    User user = new User("why", "123");
    // 将 Object 转换为 Json
    String jsonUser = new ObjectMapper().writeValueAsString(user);
    redisTemplate.opsForValue().set("user", jsonUser);
    System.out.println(redisTemplate.opsForValue().get("user"));
}

在这里插入图片描述

在这里插入图片描述

● 传输序列化对象
// 序列化的实体类
@Component
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
    private String name;
    private String password;
}
@Test
void test() throws JsonProcessingException {
    User user = new User("why", "123");
    redisTemplate.opsForValue().set("user", user);
    System.out.println(redisTemplate.opsForValue().get("user"));
}

在这里插入图片描述

在这里插入图片描述

● Redis 用户端乱码问题

在这里插入图片描述

在这里插入图片描述

(4) 自定义配置类

@Configuration
public class RedisConfig {

    // 自定义 redisTemplate, 修改 RedisAutoConfiguration 中的 Bean
    @Bean
    @SuppressWarnings("all")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        // <String, Object> 类型便于开发
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        // Json 序列化配置
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        // String 序列化配置
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // key 采用 string 的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash 的 key 采用 string 的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value 采用 jackson 的序列化方式
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // hash 的 value 采用 jackson 的序列化方式
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}
@Test
void test() throws JsonProcessingException {
    User user = new User("why", "123");
    redisTemplate.opsForValue().set("user", user);
    System.out.println(redisTemplate.opsForValue().get("user"));
}

在这里插入图片描述

在这里插入图片描述


http://www.niftyadmin.cn/n/5050272.html

相关文章

内存对齐--面试常问问题和笔试常考问题

1.内存对齐的意义 C 内存对齐的主要意义可以简练概括为以下几点&#xff1a; 提高访问效率&#xff1a;内存对齐可以使数据在内存中以更加紧凑的方式存储&#xff0c;从而提高了数据的访问效率。处理器通常能够更快地访问内存中对齐的数据&#xff0c;而不需要额外的字节偏移计…

ElementUI首页导航和左侧菜单静态页面的实现,以及Mockjs和总线的介绍

目录 前言 一. Mock.js 1.1 什么是Mock.js 1.2 Mockjs的安装与配置 1.2.1 安装Mock.js 1.2.2 引入Mock.js 1.3 Mockjs的使用 1.3.1 定义数据测试文件 1.3.2 mock拦截ajax请求 二. 首页导航以及左侧菜单的搭建 2.1 什么是总线 2.2 创建三个vue组件 首页AppMain.vue组…

SpringBoot全局异常处理源码

SpringBoot全局异常处理源码 一、SpringMVC执行流程二、SpringBoot源码跟踪三、自定义优雅的全局异常处理脚手架starter自定义异常国际化引入封装基础异常封装基础异常扫描器&#xff0c;并注册到ExceptionHandler中项目分享以及改进点 一、SpringMVC执行流程 今天这里叙述的全…

mutt+msmtp配置smtp tls starttls模式发邮件

原文地址 muttmsmtp配置smtp tls starttls模式发邮件 - ismeoh Blog apt-get install msmtp mutt -y cd /root/ vim .muttrc ----- set sendmail"/usr/bin/msmtp" set use_fromyes #发件人名字 set realname"Ryan Wang" #发件人地址 set fromxxxxxxxxx163…

maven settings.xml文件(包含了配置阿里云镜像)

mac 的 settings.xml 我配置的位置是&#xff1a; /Applications/IntelliJ IDEA.app/Contents/plugins/maven/lib/maven3/conf/settings.xml 然后 local repository 我配置的位置是&#xff1a; /Applications/IntelliJ IDEA.app/Contents/plugins/maven/lib/maven3/conf/repos…

浅谈基于LoRa技术下智能建筑能耗管理系统的分析与设计

安科瑞 华楠 摘要&#xff1a;城市建设步伐加快背景下&#xff0c;对城市建筑能耗管理系统的应用提出更高要求。从当前各类公共建筑物运营情况看&#xff0c;能源消耗问题仍较为突出&#xff0c;传统依托于计算机、测控单元与通讯设备单位工具的系统管理模式&#xff0c;并不能…

jar简易自检程序

title: “Jar简易自检程序” createTime: 2022-01-05T14:44:0108:00 updateTime: 2022-01-05T14:44:0108:00 draft: false author: “name” tags: [“shell”,“java”] categories: [“shell”] description: “测试的” jar 简易自检程序 脚本 #!/bin/sh#linecat ./pid/f…

Spring 学习(五)JavaConfig 实现配置

1. 使用 JavaConfig 实现配置 JavaConfig 是 Spring 项目的一个子项目&#xff0c;Spring 4 后成为核心功能。 注意&#xff1a; 如果开启包扫描&#xff0c;加载配置类以后就可以通过反射拿到配置类中的对象了。Bean 只写在方法上&#xff0c;返回的是一个对象&#xff0c;但…