Spring Boot整合Redis


一、Redis概述

Redis是一个开源(BSD许可)的、内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件,并提供多种语言的API。

Redis支持多种类型的数据结构,如 字符串(strings)、散列(hashes)、列表(lists)、集合(sets)、有序集合(sorted sets)与范围查询、bitmaps、 hyperloglogs 和 地理空间(geospatial)、索引半径查询。

Redis 内置了复制(replication),LUA脚本(Lua scripting),LRU驱动事件(LRU eviction),事务(transactions) 和不同级别的磁盘持久化(persistence), 并通过 Redis哨兵(Sentinel)和自动 分区(Cluster)提供高可用性(high availability)。

Redis官网与在线教程

官网:https://redis.io/
中文网站:http://www.redis.cn/
在线教程:https://www.redis.net.cn/tutorial/3502.html

二、使用Spring Boot 整合 Redis

(一)搭建Redis环境

请参考《Redis和Redis可视化管理工具的下载和安装》

(二)下载和安装Redis可视化管理工具

请参考《Redis和Redis可视化管理工具的下载和安装》

(三)创建Spring Boot项目RedisDemo

设置项目配置
在这里插入图片描述

添加项目依赖
在这里插入图片描述
完成项目初始化
在这里插入图片描述

(四)创建实体类

在net.army.boot包里创建bean子包
在这里插入图片描述

1、创建地址实体类 - Address

在net.army.boot.bean包里创建地址实体类Address
在这里插入图片描述

package net.army.boot.bean;

import org.springframework.data.redis.core.index.Indexed;

/**
 * 功能:地址实体类
 * 日期:2023年06月16日
 * 作者:梁辰兴
 */
public class Address {
    @Indexed
    private String country; //国家
    @Indexed
    private String city; //城市

    public Address(String country, String city) {
        this.country = country;
        this.city = city;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    @Override
    public String toString() {
        return "Address{" +
                "country='" + country + '\'' +
                ", city='" + city + '\'' +
                '}';
    }
}

注意:索引类Indexed不要导入错误 - import org.springframework.data.redis.core.index.Indexed;

2、创建家庭实体类 - Family

在net.army.boot.bean包里创建家庭实体类Family
在这里插入图片描述

package net.army.boot.bean;

import org.springframework.data.redis.core.index.Indexed;

/**
 * 功能:家庭实体类
 * 日期:2023年06月16日
 * 作者:梁辰兴
 */
public class Family {
    @Indexed
    private String type; //成员类型
    @Indexed
    private String name; //成员名

    public Family(String type, String name) {
        this.type = type;
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Family{" +
                "type='" + type + '\'' +
                ", name='" + name + '\'' +
                '}';
    }
}

3、创建个人实体类 - Person

在net.army.boot.bean包里创建个人实体类Person
在这里插入图片描述

package net.army.boot.bean;

import org.springframework.data.annotation.Id;
import org.springframework.data.redis.core.RedisHash;
import org.springframework.data.redis.core.index.Indexed;

import java.util.List;

/**
 * 功能:个人实体类
 * 日期:2023年06月16日
 * 作者:梁辰兴
 */
@RedisHash("persons")
public class Person {
    @Id  //主键
    private String id;
    //生成二级索引,方便查询
    @Indexed
    private String firstName; //名
    @Indexed
    private String lastName; //姓
    private Address address; //家庭地址
    private List<Family> familyList; //家庭成员

    public Person(String id, String firstName, String lastName, Address address, List<Family> familyList) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.address = address;
        this.familyList = familyList;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public List<Family> getFamilyList() {
        return familyList;
    }

    public void setFamilyList(List<Family> familyList) {
        this.familyList = familyList;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id='" + id + '\'' +
                ", firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", address=" + address +
                ", familyList=" + familyList +
                '}';
    }
}

说明:注解@RedisHash(“persons”),表明在redis数据库中开启一个persons的内存空间,所有person操作相关的数据均保存在此空间(redis是内存数据库)。

(五)创建仓库接口 - PersonRepository

在net.army.boot包里创建repository子包,再在子包下创建PersonRepository接口
在这里插入图片描述

package net.army.boot.repository;

import net.army.boot.bean.Person;
import org.springframework.data.repository.CrudRepository;

/**
 * 功能:个人仓库接口
 * 日期:2023年06月16日
 * 作者:梁辰兴
 */
public interface PersonRepository extends CrudRepository<Person, String> {
}

(六)在全局配置文件配置Redis属性

在这里插入图片描述

spring.redis.port=6379
spring.redis.host=127.0.0.1
spring.redis.password=

(七)在测试类里编写测试方法

点开测试类RedisDemoApplicationTests
在这里插入图片描述
注入PersonRepository实例
在这里插入图片描述

@Autowired // 注入个人仓库
private PersonRepository personRepository;

1、创建测试方法testAddPerson()

@Test                                                                                                         
public void testAddPerson() {                                                                                 
    // 添加第一个人                                                                                                 
    Address address = new Address("中国", "泸州");                                                                
    Family family1 = new Family("儿子", "张晓刚");                                                                 
    Family family2 = new Family("女儿", "张晓霞");                                                                 
    List<Family> familyList = new ArrayList<Family>();                                                        
    familyList.add(family1);                                                                                  
    familyList.add(family2);                                                                                  
    Person person = new Person("1", "无忌", "张", address, familyList);                                          
    personRepository.save(person);                                                                            
                                                                                                              
    // 添加第二个人                                                                                                 
    address = new Address("中国", "上海");                                                                        
    family1 = new Family("儿子", "李功晨");                                                                        
    family2 = new Family("女儿", "李晓丽");                                                                        
    familyList = new ArrayList<Family>();                                                                     
    familyList.add(family1);                                                                                  
    familyList.add(family2);                                                                                  
    person = new Person("2", "承鹏", "李", address, familyList);                                                 
    personRepository.save(person);                                                                            
                                                                                                              
    // 添加第三个人                                                                                                 
    address = new Address("中国", "北京");                                                                        
    family1 = new Family("儿子", "唐玉海");                                                                        
    family2 = new Family("女儿", "唐雨涵");                                                                        
    familyList = new ArrayList<Family>();                                                                     
    familyList.add(family1);                                                                                  
    familyList.add(family2);                                                                                  
    person = new Person("3", "大明", "唐", address, familyList);                                                 
    personRepository.save(person);                                                                            
                                                                                                              
    // 添加第四个人                                                                                                 
    address = new Address("中国", "北京");                                                                        
    family1 = new Family("儿子", "张大明");                                                                        
    family2 = new Family("女儿", "张丽丽");                                                                        
    familyList = new ArrayList<Family>();                                                                     
    familyList.add(family1);                                                                                  
    familyList.add(family2);                                                                                  
    person = new Person("4", "文勇", "张", address, familyList);                                                 
    personRepository.save(person);                                                                            
                                                                                                              
    System.out.println("成功地添加了4条记录~");                                                                        
}                                                                                                                                                                                           

运行测试方法,查看结果
在这里插入图片描述
打开Redis可视化工具查看
在这里插入图片描述
在这里插入图片描述

2、创建测试方法testFindAll()

@Test                                                     
public void testFindAll() {                               
	Iterable<Person> persons = personRepository.findAll();
	persons.forEach(person -> System.out.println(person));
}                                                        

运行测试方法,查看结果
在这里插入图片描述

3、测试personRespository的其它方法

在这里插入图片描述
创建测试方法testFindById()

@Test
public void testFindById() {
    Optional<Person> person = personRepository.findById("2");
	System.out.println(person);
}

运行测试方法,查看结果
在这里插入图片描述

(八)测试自定义个性化查询方法

1、在PersonRepository接口定义方法

package net.army.boot.repository;

import net.army.boot.bean.Person;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.CrudRepository;

import java.util.List;

/**
 * 功能:个人仓库接口
 * 日期:2023年06月16日
 * 作者:梁辰兴
 */
public interface PersonRepository extends CrudRepository<Person, String> {
    //自定义个性化查询,方法名需要符合特定的规范
    List<Person> findByLastName(String lastName);
    Page<Person> findPersonByLastName(String lastName, Pageable pageable);
    List<Person> findPersonByLastNameAndFirstName(String lastName, String firstName);
    List<Person> findByAddress_City(String city);
    List<Person> findByFamilyList_Name(String name);
}

2、在测试类创建测试方法testFindPersonByLastName()

@Test                                                                        
public void testFindPersonByLastName() {                                     
	// 降序排序                                                                  
	Sort.Direction sort = Sort.Direction.DESC;                               
	// 创建分页器                                                                 
	Pageable pageable = PageRequest.of(0, 2, sort, "id");                    
	// 获取页面                                                                  
	Page<Person> page = personRepository.findPersonByLastName("张", pageable);
	// 输出页面内容                                                                
	for (Person person : page.getContent()) {                                
		System.out.println(person);                                          
	}                                                                        
}                                                                            

运行测试方法,查看结果
在这里插入图片描述

三、练习

任务1、在测试类创建测试方法testFindByLastName()

查找姓“张”的记录
在这里插入图片描述

任务2、在测试类创建测试方法testFindPersonByLastNameAndFirstName()

查找lastName为“唐”,firstName为“大明”的记录
在这里插入图片描述

任务3、在测试类创建测试方法testFindByAddress_City()

查找“北京”的记录
在这里插入图片描述

任务4、在测试类创建测试方法testFindByFamilyList_Name()

查找“唐雨涵”
在这里插入图片描述

  • 21
    点赞
  • 64
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot 可以很方便地与 Redis 进行集成。以下是一个简单的 Spring Boot 整合 Redis 的示例: 1. 添加 Redis 依赖 在 `pom.xml` 添加 Redis 相关依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 配置 Redis 连接信息 在 `application.properties` 文件中配置 Redis 的连接信息: ```properties spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= ``` 如果 Redis 没有设置密码,则 `spring.redis.password` 可以不用配置。 3. 编写 Redis 配置类 创建一个 Redis 配置类,用于配置 RedisTemplate 和 RedisConnectionFactory: ```java @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new GenericToStringSerializer<>(Object.class)); return redisTemplate; } @Bean public RedisConnectionFactory redisConnectionFactory() { RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(); redisStandaloneConfiguration.setHostName("localhost"); redisStandaloneConfiguration.setPort(6379); return new JedisConnectionFactory(redisStandaloneConfiguration); } } ``` 4. 使用 RedisTemplate 操作 Redis 在需要使用 Redis 的地方注入 RedisTemplate,然后就可以使用其提供的方法操作 Redis 了: ```java @RestController @RequestMapping("/redis") public class RedisController { @Autowired private RedisTemplate<String, Object> redisTemplate; @GetMapping("/set") public String set(String key, String value) { redisTemplate.opsForValue().set(key, value); return "success"; } @GetMapping("/get") public String get(String key) { Object value = redisTemplate.opsForValue().get(key); return value != null ? value.toString() : ""; } } ``` 以上示例中,我们使用了 RedisTemplate 的 `opsForValue` 方法来进行 Redis 的读写操作。 这样,我们就完成了 Spring Boot 整合 Redis 的操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梁辰兴

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值