开发喵星球

Spring Boot整合Redis(Service封装)

一、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/

原始SpringBoot访问Redis

@Resource
private RedisTemplate<String,Object> redisTemplate;
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.opsForValue().set("myKey","kaifamiao");
redisTemplate.opsForValue().get("myKey"));

为什么要用Service层

在Spring Boot中,使用Service层的好处显著,尤其在构建复杂的企业级应用时。以下是一些主要好处:

  1. 分层架构Service层作为SpringBoot应用的一个组成部分,帮助实现分层架构。这种架构分离了业务逻辑数据访问表示层,使得代码更加模块化,易于管理和维护。
  2. 业务逻辑封装Service层允许开发者在一个集中的位置封装业务逻辑,从而使得业务逻辑与数据访问代码分离。这样可以更容易地维护和更新业务规则,而不影响其他系统部分。
  3. 重用性和模块化:通过在Service层中定义功能,可以在不同的控制器之间重用这些服务。这增加了代码的模块化和重用性,减少了重复代码。
  4. 易于测试Service层使得对业务逻辑的单元测试变得更加简单。由于业务逻辑从表示层和数据访问层中分离出来,因此可以独立于用户界面和数据库进行测试。
  5. 事务管理:在Service层中处理事务管理使得代码更加清晰,有助于维护数据的一致性和完整性。Spring提供了强大的事务管理功能,可以很容易地应用于服务层。
  6. 灵活性和可维护性:通过定义清晰的服务接口,可以在不改变使用这些服务的客户端代码的情况下,更改底层的业务逻辑实现。这使得应用程序更灵活,易于适应变化的需求。
  7. 更好的隔离级别:在复杂的应用中,Service层可以作为不同组件之间的隔离层,确保高级别组件不会直接依赖于低级别的实现细节。

总体而言,Service层在SpringBoot应用中提供了一种有效的方式来组织和管理业务逻辑,使得应用程序更加结构化、可维护和可扩展。

二、使用Spring Boot 整合 Redis

设置远程

通常情况下不需要远程设置Redis但是这里为演示

调整Redis远程访问

设置密码

requirepass 123456

允许远程访问

bind 0.0.0.0

注释127.0.0.1

#127.0.0.1

取消保护

protected-mode no

工程设置

image-20231123135600048

所需依赖

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
 <dependency>
  <dependency>
            <groupId>jakarta.persistence</groupId>
            <artifactId>jakarta.persistence-api</artifactId>
            <version>2.2.3</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.5</version>
        </dependency>

配置数据连接application.properties

spring.redis.port=端口
spring.redis.host=地址
spring.redis.password=密码

三、创建实体类

Address.java

package com.example.redis_demo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.redis.core.index.Indexed;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Address {
    @Indexed
    private String country; //国家
    @Indexed
    private String city; //城市

}

Family.java

package com.example.redis_demo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.redis.core.index.Indexed;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Family {
    @Indexed
    private String type; //成员类型
    @Indexed
    private String name; //成员名
}

Person.java

package com.example.redis_demo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
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;

@Data
@AllArgsConstructor
@NoArgsConstructor
@RedisHash("persons")
@ToString
public class Person {
    @javax.persistence.Id
    @Id  //主键
    private Long id;
    //生成二级索引,方便查询
    @Indexed
    private String firstName; //名
    @Indexed
    private String lastName; //姓
    private Address address; //地址
    private List<Family> familyList; //家庭成员

    private Family family;
    //构造函数可选
    public Person(Long id, String firstName, String lastName, Address address, List<Family> familyList1) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.address = address;
    }
    public Person(Long id, String firstName, String lastName, List familyList) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.familyList = familyList;
    }

}

四、创建 PersonRepository

PersonRepository.java

package com.example.redis_demo;

import org.springframework.data.repository.CrudRepository;

public interface PersonRepository extends CrudRepository<Person, String> {
}

五、创建Service

PersonService.java

package com.example.redis_demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PersonService {

    private final PersonRepository personRepository;

    @Autowired
    public PersonService(PersonRepository personRepository) {
        this.personRepository = personRepository;
    }

    public Person savePerson(Person person) {
        return personRepository.save(person);
    }

    public Person getPerson(String id) {
        return personRepository.findById(id).orElse(null);
    }

    public Iterable<Person> getAllPersons () {
        return personRepository.findAll();
    }

    public void deletePerson(String id) {
        personRepository.deleteById(id);
    }

    // 可以根据需要添加更多方法
}

六、测试

添加对象

personService.savePerson(对象);

Address address1 = new Address("中国", "北京");
Family family1 = new Family("父亲", "张三");
List<Family> familyList1 = new ArrayList<Family>();
familyList1.add(family1);
Person person1 =new Person(1L, "无忌", "张", address1,familyList1);
personService.savePerson(person1);
Address address2 = new Address("中国", "北京");
Person person2 =new Person(2L, "峰", "乔",address2, familyList1);
personService.savePerson(person2);
Family family3 = new Family("父亲", "郭");
List<Family> familyList3 = new ArrayList<Family>();
familyList3.add(family3);
Person person3 =new Person(3L, "靖", "郭",familyList3);
personService.savePerson(person3);
Address address = new Address("中国", "宜宾");
Family family4 = new Family("儿子", "郭晓刚");
Family family5 = new Family("女儿", "郭晓霞");
List<Family> familyList = new ArrayList<Family>();
familyList.add(family4);
familyList.add(family5);
Person person4 = new Person(4L, "无忌", "郭    ", address, familyList);
personService.savePerson(person4);

查看redis

image-20231123141827176

运行

personService.getAllPersons().forEach(person -> System.out.println(person.toString()));

输出

Person(id=1, firstName=无忌, lastName=张, address=Address(country=中国, city=北京), familyList=null, family=null)
Person(id=2, firstName=峰, lastName=乔, address=Address(country=中国, city=北京), familyList=null, family=null)
Person(id=3, firstName=靖, lastName=郭, address=null, familyList=[Family(type=父亲, name=郭)], family=null)
Person(id=4, firstName=无忌, lastName=郭    , address=Address(country=中国, city=宜宾), familyList=null, family=null)

Json格式

 // 创建ObjectMapper对象
        ObjectMapper objectMapper = new ObjectMapper();
        // 获取所有的Person对象
        Iterable<Person> persons = personService.getAllPersons();
        // 遍历每个Person对象并将其转换为JSON
        List<String> jsonList = new ArrayList<>();
        for (Person person : persons) {
            // 将Person对象转换为JSON字符串
            String json = objectMapper.writeValueAsString(person);
            System.out.println(json);
        }

输出

{"id":1,"firstName":"无忌","lastName":"张","address":{"country":"中国","city":"北京"},"familyList":null,"family":null}
{"id":2,"firstName":"峰","lastName":"乔","address":{"country":"中国","city":"北京"},"familyList":null,"family":null}
{"id":3,"firstName":"靖","lastName":"郭","address":null,"familyList":[{"type":"父亲","name":"郭"}],"family":null}
{"id":4,"firstName":"无忌","lastName":"郭    ","address":{"country":"中国","city":"宜宾"},"familyList":null,"family":null}

gitee地址:https://gitee.com/kaifamiaos/redis_demo

七、完整Test

package com.example.redis_demo;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.List;

@SpringBootTest

class RedisDemoApplicationTests {
    @Autowired
    private PersonService personService;

    @Test
    public void testAddPerson() throws JsonProcessingException {
        Address address1 = new Address("中国", "北京");
        Family family1 = new Family("父亲", "张三");
        List<Family> familyList1 = new ArrayList<Family>();
        familyList1.add(family1);
        Person person1 =new Person(1L, "无忌", "张", address1,familyList1);
        personService.savePerson(person1);

        Address address2 = new Address("中国", "北京");
        Person person2 =new Person(2L, "峰", "乔",address2, familyList1);
        personService.savePerson(person2);

        Family family3 = new Family("父亲", "郭");
        List<Family> familyList3 = new ArrayList<Family>();
        familyList3.add(family3);
        Person person3 =new Person(3L, "靖", "郭",familyList3);
        personService.savePerson(person3);

        Address address = new Address("中国", "宜宾");
        Family family4 = new Family("儿子", "郭晓刚");
        Family family5 = new Family("女儿", "郭晓霞");
        List<Family> familyList = new ArrayList<Family>();
        familyList.add(family4);
        familyList.add(family5);
        Person person4 = new Person(4L, "无忌", "郭    ", address, familyList);
        personService.savePerson(person4);


        personService.getAllPersons().forEach(person -> System.out.println(person.toString()));

        // 创建ObjectMapper对象
        ObjectMapper objectMapper = new ObjectMapper();
        // 获取所有的Person对象
        Iterable<Person> persons = personService.getAllPersons();
        // 遍历每个Person对象并将其转换为JSON
        List<String> jsonList = new ArrayList<>();
        for (Person person : persons) {
            // 将Person对象转换为JSON字符串
            String json = objectMapper.writeValueAsString(person);
            System.out.println(json);
        }


    }

}

   
分类:技术栈 作者:开发喵 发表于:2023-11-22 18:54:19 阅读量:84
  >>


powered by kaifamiao