Caching and paging operations are used in redis

Operation:

Springboot+mp+redis

// student table id sname cid

//Class table cid cname

Cache annotations are generally in the service layer

  1. Query all classes and all information in the class and cache it in rdis

(no pagination required)

  1. Stream stream obtains the data on the second page (there are 2 pieces of data on each page)

MySQL part

Project dependency:pom file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.15</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.aaa</groupId>
    <artifactId>day1025_1</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>day1025_1</name>
    <description>day1025_1</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- Add a Redis starter component -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.15</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.2.1</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-util</artifactId>
            <version>9.3.7.v20160115</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.5</version>
            <scope>test</scope>
        </dependency>
        <!-- Automatically generated -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.3</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.5.3</version>
        </dependency>
        <!-- Template -->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.3</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.26</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

properties file

spring.redis.host=192.168.197.33
spring.redis.password=yyl
spring.redis.database=6

server.port=8082

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/bbb?serverTimezone=UTC & amp;useUnicode=true & amp;characterEncoding=utf-8 & amp;useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
#   json?
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT + 8
spring.jackson.serialization.write-date-keys-as-timestamps=false
#logging.level.com.baomidou.ant.test.dao=debug
#mybatis-plus
# r_name rName setRName
mybatis-plus.configuration.map-underscore-to-camel-case=true
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#mybatis-plus.configuration.log-impl=
mybatis-plus.mapper-locations=classpath:/mapper/*.xml
# ?0 ?1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
mybatis-plus.global-config.db-config.logic-delete-value=1

config layer

package com.aaa.config;/**
 * @program: eleven-project
 * @description:
 * @author: 寮纺煅
 * @create: 2023/10/24
 **/

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

/**
 * @program: Redis-1
 * @description:
 * @author: Mr.Like
 * @create: 2023-10-24 14:45
 **/

@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        //Specify the domain to be serialized, field, get and set, and the modifier range, ANY includes private and public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // Specify the type of serialized input. The class must be non-final modified. Final modified classes, such as String, Integer, etc., will throw exceptions.
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setConnectionFactory(factory);
        //Key serialization method
        template.setKeySerializer(redisSerializer);
        //value serialization
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //value hashmap serialization
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }

    /**
     * Caching processing
     * @param factory
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//Solve the problem of query cache conversion exception
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
// Configure serialization (to solve the problem of garbled characters), expiration time is 600 seconds
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(60))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }
}

controller layer

studentcontroller:

package com.aaa.controller;


import com.aaa.entity.Student;
import com.aaa.service.IStudentService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * Front-end controller
 *</p>
 *
 * @author
 * @since 2023-10-25
 */
@RestController
@RequestMapping("/student")
public class StudentController {
    @Resource
    private IStudentService studentService;

    @GetMapping("/{id}")
    public List<Student> getStudentByGid(@PathVariable Integer id) {
        return studentService.getStudentByGid(id);
    }

    @GetMapping("/{id}/{index}/{size}")
// paging operation
    public List<Student> PageStudentByStreamtByGid(@PathVariable Integer id, @PathVariable Integer index, @PathVariable Integer size) {
        return studentService.PageStudentByStream(id, index, size);
    }

}

gradecontroller

package com.aaa.controller;


import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * Front-end controller
 *</p>
 *
 * @author
 * @since 2023-10-25
 */
@RestController
@RequestMapping("/grade")
public class GradeController {

}

entity layer

student entity class

package com.aaa.entity;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

/**
 * <p>
 *
 *</p>
 *
 * @author
 * @since 2023-10-25
 */
@Data
@TableName("student")
public class Student implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    @TableField("sname")
    private String sname;

    @TableField("age")
    private Integer age;

    @TableField("cid")
    private Integer cid;

    @TableField("cname")
    private String cname;
    
}

grade entity class

package com.aaa.entity;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

/**
 * <p>
 *
 *</p>
 *
 * @author
 * @since 2023-10-25
 */
@Data

@TableName("grade")
public class Grade implements Serializable {



    @TableId(value = "cid", type = IdType.AUTO)
    private Integer cid;

    @TableField("cname")
    private String cname;


}

mapper layer

studentmapper

package com.aaa.mapper;

import com.aaa.entity.Student;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.cache.annotation.Cacheable;

import java.util.List;

/**
 * <p>
 * Mapper interface
 *</p>
 *
 * @author
 * @since 2023-10-25
 */
public interface StudentMapper extends BaseMapper<Student> {
    @Cacheable(value = "getStudentByGid", key = "#id")
    List<Student> getStudentsByGid(Integer id);

}

grademapper

package com.aaa.mapper;

import com.aaa.entity.Grade;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

/**
 * <p>
 * Mapper interface
 *</p>
 *
 * @author
 * @since 2023-10-25
 */
public interface GradeMapper extends BaseMapper<Grade> {

}

service layer

studentservice interface

package com.aaa.service;

import com.aaa.entity.Student;
import com.baomidou.mybatisplus.extension.service.IService;

import java.util.List;

/**
 * <p>
 * Service category
 *</p>
 *
 * @author
 * @since 2023-10-25
 */
public interface IStudentService extends IService<Student> {
    List<Student> getStudentByGid(Integer id);
// paging operation
    List<Student> PageStudentByStream(Integer id,Integer index,Integer size);
}
studentserviceimpl implementation class
package com.aaa.service.impl;

import com.aaa.entity.Student;
import com.aaa.mapper.StudentMapper;
import com.aaa.service.IStudentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * Service implementation class
 *</p>
 *
 * @author
 * @since 2023-10-25
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements IStudentService {
    @Resource
    private StudentMapper studentMapper;
    @Override
    public List<Student> getStudentByGid(Integer id) {
        return studentMapper.getStudentsByGid(id);
    }

    @Override
    public List<Student> PageStudentByStream(Integer id, Integer index, Integer size) {
        //Query all students
        List<Student> studnets = getStudentByGid(id);

        List<Student> list = new ArrayList<>();

        studnets.forEach(student -> {
            if (studnets.indexOf(student) >= (index - 1) * size & & studnets.indexOf(student) <= index * size - 1) {
                list.add(student);
            }
        });
        return list;
    }
}

gradeservice interface

package com.aaa.service;

import com.aaa.entity.Grade;
import com.baomidou.mybatisplus.extension.service.IService;

/**
 * <p>
 * Service category
 *</p>
 *
 * @author
 * @since 2023-10-25
 */
public interface IGradeService extends IService<Grade> {

}
gradeserviceimpl implementation class
package com.aaa.service.impl;

import com.aaa.entity.Grade;
import com.aaa.mapper.GradeMapper;
import com.aaa.service.IGradeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 * Service implementation class
 *</p>
 *
 * @author
 * @since 2023-10-25
 */
@Service
public class GradeServiceImpl extends ServiceImpl<GradeMapper, Grade> implements IGradeService {

}

studentmapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.aaa.mapper.StudentMapper">

    <select id="getStudentsByGid" resultType="com.aaa.entity.Student" parameterType="java.lang.Integer">
        select s.*, g.cname
        FROM students
                 RIGHT JOIN grade g
                            on g.cid = s.cid
        where g.cid = #{cid}
    </select>

</mapper>

springboot running class

package com.aaa;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching //Enable caching
@MapperScan("com.aaa.mapper")
public class Day10251Application {

    public static void main(String[] args) {
        SpringApplication.run(Day10251Application.class, args);
    }

}

Run:

Use the software postman to establish a connection with the idea project

Run the springboot project in idea

As shown below:

Then execute it according to the path in the project in postman

As shown below:

At this time, clear the console in the project as shown below

Run postman again

At this time, you can see that there is no data in the console.

So at this time, it is determined that the cache is successful.