Spring boot 集成Redis

目录

前言

一、如何集成?

1.引入包

2.添加配置

3.添加配置类

4.使用示例

二、为什么?

1.配置文件的参数怎么填写?

2.为什么默认是Lettuce而不是Jedis?

3.什么时候会自动装配?

总结




前言

为了怕自己忘记,当做笔记用。

 



一、如何集成?

1.引入包

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

2.添加配置

application.yaml

spring:
  #redis
  redis:
    lettuce:
        pool:
            max-active: 10
            max-idle: 10
            max-wait: 1
            min-idle: 0
    cluster:
        max-redirects: 3
        nodes: 192.168.3.170:6379,192.168.3.172:6379,192.168.3.175:6379,192.168.3.170:6389,192.168.3.172:6389,192.168.3.175:6389
    password: xxxxxx



3.添加配置类

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory){
        // 设置序列化
        Jackson2JsonRedisSerializer<Object> 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);
        // 配置redisTemplate
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);
        RedisSerializer<?> stringSerializer = new StringRedisSerializer();
        // key序列化
        redisTemplate.setKeySerializer(stringSerializer);
        // value序列化
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        // Hash key序列化
        redisTemplate.setHashKeySerializer(stringSerializer);
        // Hash value序列化
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

4.使用示例

二、为什么?



1.配置文件的参数怎么填写?

在springboot的自动装配已经集成,所以看这个类RedisProperties就可以知道怎么配置。在这个包中:package org.springframework.boot.autoconfigure.data.redis;

2.为什么默认是Lettuce而不是Jedis?

因为在RedisAutoConfigration中第一个引入的是LettuceConnectionConfiguation。

并且LettuceConnectionConfiguation和JedisConnectionConfiguration中都用这个注解来标注@ConditionalOnMissingBean,当lettuce的存在后jedis就不会注入,防止多个注入。

3.什么时候会自动装配?

在spring.factories中的org.springframework.boot.autoconfigure.EnableAutoConfiguration=\

这里已经写死了会加载这个RedisAutoConfiguation类。

当引入这个类RedisOperations 的时候就会自动装配,@ConditionnalOnClass这个注解的作用。

而RedisOperations 这个类是在spring-data-redis这个包中,而spring-data-redis是在 spring-boot-starter-data-redis引入。

        <!--redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <!-- This module was also published with a richer model, Gradle metadata,  -->
  <!-- which should be used instead. Do not delete the following line which  -->
  <!-- is to indicate to Gradle or any Gradle module metadata file consumer  -->
  <!-- that they should prefer consuming it instead. -->
  <!-- do_not_remove: published-with-gradle-metadata -->
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
  <version>2.3.2.RELEASE</version>
  <name>spring-boot-starter-data-redis</name>
  <description>Starter for using Redis key-value data store with Spring Data Redis and the Lettuce client</description>
  <url>https://spring.io/projects/spring-boot</url>
  <organization>
    <name>Pivotal Software, Inc.</name>
    <url>https://spring.io</url>
  </organization>
  <licenses>
    <license>
      <name>Apache License, Version 2.0</name>
      <url>https://www.apache.org/licenses/LICENSE-2.0</url>
    </license>
  </licenses>
  <developers>
    <developer>
      <name>Pivotal</name>
      <email>info@pivotal.io</email>
      <organization>Pivotal Software, Inc.</organization>
      <organizationUrl>https://www.spring.io</organizationUrl>
    </developer>
  </developers>
  <scm>
    <connection>scm:git:git://github.com/spring-projects/spring-boot.git</connection>
    <developerConnection>scm:git:ssh://git@github.com/spring-projects/spring-boot.git</developerConnection>
    <url>https://github.com/spring-projects/spring-boot</url>
  </scm>
  <issueManagement>
    <system>GitHub</system>
    <url>https://github.com/spring-projects/spring-boot/issues</url>
  </issueManagement>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
      <version>2.3.2.RELEASE</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-redis</artifactId>
      <version>2.3.2.RELEASE</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>io.lettuce</groupId>
      <artifactId>lettuce-core</artifactId>
      <version>5.3.2.RELEASE</version>
      <scope>compile</scope>
    </dependency>
  </dependencies>
</project>



总结

提示:这里对文章进行总结:
例如:备忘

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Boot可以很方便地集成Redis,只需要在pom.xml中添加相应的依赖,配置Redis连接信息,就可以使用RedisTemplate等工具类来操作Redis数据库。 具体步骤如下: 1. 在pom.xml中添加Redis依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 配置Redis连接信息,可以在application.properties中添加以下配置: ``` spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password= ``` 3. 在代码中使用RedisTemplate等工具类来操作Redis数据库,例如: ``` @Autowired private RedisTemplate<String, Object> redisTemplate; public void set(String key, Object value) { redisTemplate.opsForValue().set(key, value); } public Object get(String key) { return redisTemplate.opsForValue().get(key); } ``` 以上就是Spring Boot集成Redis的基本步骤,具体使用可以根据实际需求进行调整。 ### 回答2: Spring Boot是一个基于Spring框架的快速开发框架,可以为我们提供很多便利的功能,其中就括了集成Redis的能力。Redis是一种开源的非关系型数据库,可以在内存中存储数据,并将其持久化到硬盘上,具有高性能和高可用性等优点。在Spring Boot集成Redis,我们可以利用Redis的缓存功能,将一些数据缓存到Redis中,以提高系统的响应速度和性能。 下面介绍如何在Spring Boot集成Redis: 1. 添加Redis依赖 在项目的pom.xml文件中添加如下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 这个依赖会自动引入Redis的相关依赖。 2. 配置Redis连接信息 在application.properties文件中添加如下配置信息: ``` # Redis 服务器地址 spring.redis.host=localhost # Redis 服务器连接端口 spring.redis.port=6379 # Redis 服务器连接密码 spring.redis.password=123456 # Redis 数据库索引(默认为0) spring.redis.database=0 ``` 这些配置信息会被Spring Boot自动加载,并生成Redis连接池,以便程序对Redis进行访问。 3. 创建RedisTemplate对象 在Spring Boot中,我们可以使用RedisTemplate对象来访问Redis数据库。它是一个泛型类,可以指定Key和Value的类型。我们可以在配置类中创建RedisTemplate对象,并对其进行初始化: ``` @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); // 设置Key和Value的序列化方式 template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return template; } } ``` 这段代码中,我们先通过@Configuration注解将这个类声明为配置类,然后使用@Bean注解在容器中创建RedisTemplate对象,并将其与RedisConnectionFactory关联。最后,我们要设置Key和Value的序列化方式,这里使用了StringRedisSerializer和GenericJackson2JsonRedisSerializer这两种序列化方式。 4. 使用RedisTemplate操作Redis 在程序中,我们可以使用RedisTemplate对象对Redis进行存储和读取操作。下面是一些常见的操作: ``` // 存储数据 redisTemplate.opsForValue().set("key", "value"); // 获取数据 Object value = redisTemplate.opsForValue().get("key"); // 删除数据 redisTemplate.delete("key"); // 批量存储数据 Map<String, Object> map = new HashMap<>(); map.put("key1", "value1"); map.put("key2", "value2"); redisTemplate.opsForValue().multiSet(map); // 批量获取数据 List<String> keys = new ArrayList<>(); keys.add("key1"); keys.add("key2"); List<Object> values = redisTemplate.opsForValue().multiGet(keys); ``` 总之,通过以上步骤,我们就可以在Spring Boot集成Redis,并且使用RedisTemplate对象对Redis进行操作,从而为我们的应用程序提供高速缓存支持,加快系统的响应速度和性能,提高系统的可用性和可扩展性。 ### 回答3: Spring Boot是一个开源的Java应用程序开发框架,它可以提供一些灵活的工具和插件来简化应用程序开发过程。而Redis是一个高性能的键值存储数据库,它支持持久化和高并发访问,在Web应用程序中经常用于缓存,分布式锁等。 Spring Boot提供了一个Spring Data Redis框架来简化Redis集成,开发者可以通过这个框架来快速集成Redis到他们的应用程序中。以下是集成步骤: 1.添加相关依赖 在Maven或Gradle中添加以下依赖,以引入Spring Data Redis所需的所有库。 Maven: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` Gradle: ```groovy implementation 'org.springframework.boot:spring-boot-starter-data-redis' ``` 2.配置连接信息 在应用程序的配置文件中配置Redis连接信息。 ```yaml spring: redis: host: localhost port: 6379 ``` 3.创建RedisTemplate 创建一个RedisTemplate Bean来进行Redis操作。可以在Spring Boot中使用RedisTemplate<String, Object>来发送和接收Redis消息,其中String 是 Redis ke 的数据类型,而Object 是 Redis value 的数据类型。 ```java @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactory); return template; } } ``` 4.使用RedisTemplate操作数据 使用RedisTemplate来进行数据的操作,例如添加、修改和删除等。以下是一些示例代码: ```java @Autowired private RedisTemplate<String, Object> redisTemplate; public void addUser(User user) { redisTemplate.opsForHash().putAll("user:" + user.getId(), BeanUtil.beanToMap(user)); redisTemplate.opsForSet().add("user:all", user.getId()); } public User getUserById(String id) { Map<Object, Object> map = redisTemplate.opsForHash().entries("user:" + id); User user = BeanUtil.mapToBean(map, User.class, true); return user; } public void deleteUserById(String id) { redisTemplate.opsForHash().delete("user:" + id); redisTemplate.opsForSet().remove("user:all", id); } ``` 总之,Spring Boot集成Redis非常简单,只需要几步即可完成。除了上面提到的步骤外,还可以更多地探索Spring Data Redis的高级用法,比如设置Redis的过期时间,管道操作等等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值