데이터 베이스 Redis springboot+mybatisplus+redis 데모 구현 방법

springboot+mybatisplus+redis 데모 구현 방법

May 29, 2023 pm 12:43 PM
redis springboot mybatisplus

1.필요한 jar 패키지를 .pom.xml

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

 

    <groupId>org.example</groupId>

    <artifactId>springboot_redis_demo</artifactId>

    <version>1.0-SNAPSHOT</version>

 

    <parent>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-parent</artifactId>

        <version>2.5.0</version>

    </parent>

 

    <dependencies>

 

        <!--web-->

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-web</artifactId>

            <version>2.5.0</version>

        </dependency>

 

        <!--mysql-->

        <dependency>

            <groupId>mysql</groupId>

            <artifactId>mysql-connector-java</artifactId>

            <version>8.0.25</version>

        </dependency>

 

        <!--jdbc-->

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-jdbc</artifactId>

            <version>2.5.0</version>

        </dependency>

 

        <!--druid-->

        <dependency>

            <groupId>com.alibaba</groupId>

            <artifactId>druid</artifactId>

            <version>1.2.6</version>

        </dependency>

 

        <!--mybatis-plus-->

        <dependency>

            <groupId>com.baomidou</groupId>

            <artifactId>mybatis-plus-boot-starter</artifactId>

            <version>3.4.3</version>

        </dependency>

 

        <!--generator-->

        <dependency>

            <groupId>com.baomidou</groupId>

            <artifactId>mybatis-plus-generator</artifactId>

            <version>3.4.1</version>

        </dependency>

 

        <!--freemarker-->

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-freemarker</artifactId>

            <version>2.5.0</version>

        </dependency>

 

        <!--redis-->

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-data-redis</artifactId>

            <version>2.5.0</version>

        </dependency>

 

        <!--lombok-->

        <dependency>

            <groupId>org.projectlombok</groupId>

            <artifactId>lombok</artifactId>

            <version>1.18.20</version>

            <scope>provided</scope>

        </dependency>

 

        <!--springboot-test-->

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-test</artifactId>

            <version>2.5.0</version>

            <scope>test</scope>

        </dependency>

 

        <!--junit-->

        <dependency>

            <groupId>junit</groupId>

            <artifactId>junit</artifactId>

            <version>4.13.2</version>

            <scope>test</scope>

        </dependency>

 

        <!--swagger2-->

        <dependency>

            <groupId>io.springfox</groupId>

            <artifactId>springfox-swagger2</artifactId>

            <version>3.0.0</version>

        </dependency>

 

        <!--swagger-ui-->

        <dependency>

            <groupId>io.springfox</groupId>

            <artifactId>springfox-swagger-ui</artifactId>

            <version>3.0.0</version>

        </dependency>

 

    </dependencies>

 

</project>

로그인 후 복사

2.application.yml 구성 정보

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

#端口

server:

  port: 1010

 

#配置数据源

spring:

  datasource:

    driver-class-name: com.mysql.cj.jdbc.Driver

    url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&serverTimezone=GMT%2B8&useSSL=false

    username: root

    password: 123456

    type: com.alibaba.druid.pool.DruidDataSource

 

  #配置redis

  redis:

    host: 127.0.0.1

    port: 6379

    database: 0

    password: 123456

로그인 후 복사

3에 붓습니다.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

package com.zengjx.project;

 

import org.mybatis.spring.annotation.MapperScan;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.cache.annotation.EnableCaching;

 

/**

 * @author fastrabbit

 * @date 2021/6/9 9:43

 */

@SpringBootApplication

@EnableCaching

@MapperScan("com.zengjx.project.*.mapper")

public class RedisApp {

 

    public static void main(String[] args) {

        SpringApplication.run(RedisApp.class, args);

    }

 

}

로그인 후 복사

4.mybatisplus 템플릿을 시작하는 데 필요한 주석 - baseQuery

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

package ${cfg.packagePath}.common;

 

import com.baomidou.mybatisplus.annotation.TableField;

import lombok.Data;

 

/**

 * @author ${author}

 * @date ${date}

 */

@Data

public class BaseQuery {

 

    /**

     * 当前页数  默认为1

     */

    @TableField(exist=false)

    private Integer page = 1;

 

    /**

     * 每页数据量  默认为10

     */

    @TableField(exist=false)

    private Integer rows =10;

 

}

로그인 후 복사

5.mybatisplus 템플릿 ——controller

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

package ${package.Controller};

 

import ${cfg.packagePath}.common.Result;

import ${package.Entity}.${entity};

import ${package.Service}.${table.serviceName};

import io.swagger.annotations.Api;

import io.swagger.annotations.ApiOperation;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

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

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

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

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

<#if restControllerStyle>

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

<#else>

import org.springframework.stereotype.Controller;

</#if>

 

import java.util.List;

<#if superControllerClassPackage??>

import ${superControllerClassPackage};

</#if>

 

/**

 * @author ${author}

 * @date ${date}

 */

@Api(tags = {"${table.comment!}"})

<#if restControllerStyle>

@RestController

<#else>

@Controller

</#if>

@RequestMapping("<#if package.ModuleName?? && package.ModuleName != "">/${package.ModuleName}</#if>/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}</#if>")

<#if kotlin>

class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()</#if>

<#else>

<#if superControllerClass??>

public class ${table.controllerName} extends ${superControllerClass} {

<#else>

public class ${table.controllerName} {

</#if>

 

    private Logger logger = LoggerFactory.getLogger(getClass());

 

    @Autowired

    private ${table.serviceName} ${(table.serviceName?substring(1))?uncap_first};

 

    /**

     * @author fastrabbit

     * @description 根据id查询单个数据

     * @date ${date}

     */

    @ApiOperation(value = "根据id查询单个数据")

    @RequestMapping(value = "/getById")

    public Result<${entity}> getById(@RequestBody ${entity} ${entity?uncap_first}){

 

        return ${(table.serviceName?substring(1))?uncap_first}.getById(${entity?uncap_first});

 

    }

 

    /**

     * @author fastrabbit

     * @description 根据查询条件查询分页数据

     * @date ${date}

     */

    @ApiOperation(value = "根据查询条件查询分页数据")

    @RequestMapping(value = "/list")

    public Result<List<${entity}>> findListByPage(@RequestBody ${entity} ${entity?uncap_first}){

 

        return ${(table.serviceName?substring(1))?uncap_first}.findListByPage(${entity?uncap_first});

 

    }

 

    /**

     * @author fastrabbit

     * @description 查询所有数据

     * @date ${date}

     */

    @ApiOperation(value = "查询所有数据")

    @RequestMapping(value = "/getAll")

    public Result<List<${entity}>> getAll(){

 

        return ${(table.serviceName?substring(1))?uncap_first}.getAll();

 

    }

 

    /**

     * @author fastrabbit

     * @description 新增单个数据

     * @date ${date}

     */

    @ApiOperation(value = "新增单个数据")

    @RequestMapping(value = "/insert", method = RequestMethod.POST)

    public Result<Object> insert(@RequestBody ${entity} ${entity?uncap_first}){

 

        return ${(table.serviceName?substring(1))?uncap_first}.insert(${entity?uncap_first});

 

    }

 

    /**

     * @author fastrabbit

     * @description 删除单个数据

     * @date ${date}

     */

    @ApiOperation(value = "删除单个数据")

    @RequestMapping(value = "/delete")

    public Result<Object> delete(@RequestBody ${entity} ${entity?uncap_first}){

 

        return ${(table.serviceName?substring(1))?uncap_first}.delete(${entity?uncap_first});

 

    }

 

    /**

     * @author fastrabbit

     * @description 修改单个数据

     * @date ${date}

     */

    @ApiOperation(value = "修改单个数据")

    @RequestMapping(value = "/update", method = RequestMethod.POST)

    public Result<Object> update(@RequestBody ${entity} ${entity?uncap_first}){

 

        return ${(table.serviceName?substring(1))?uncap_first}.update(${entity?uncap_first});

 

    }

 

 }

</#if>

로그인 후 복사

6.mybatisplus 템플릿——entity

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

package ${package.Entity};

 

<#list table.importPackages as pkg>

import ${pkg};

</#list>

<#if swagger2>

import io.swagger.annotations.ApiModel;

import io.swagger.annotations.ApiModelProperty;

</#if>

import ${cfg.packagePath}.common.BaseQuery;

<#if entityLombokModel>

import lombok.Data;

import lombok.EqualsAndHashCode;

    <#if chainModel>

import lombok.experimental.Accessors;

    </#if>

</#if>

 

/**

 * @author ${author}

 * @date ${date}

 */

<#if entityLombokModel>

@Data

    <#if superEntityClass??>

@EqualsAndHashCode(callSuper = true)

    <#else>

@EqualsAndHashCode(callSuper = false)

    </#if>

    <#if chainModel>

@Accessors(chain = true)

    </#if>

</#if>

<#if table.convert>

@TableName("${table.name}")

</#if>

<#if swagger2>

@ApiModel(value="${entity}对象", description="${table.comment!}")

</#if>

<#if superEntityClass??>

public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}></#if> {

<#elseif activeRecord>

public class ${entity} extends Model<${entity}> {

<#else>

public class ${entity} extends BaseQuery implements Serializable {

</#if>

 

<#if entitySerialVersionUID>

    private static final long serialVersionUID = 1L;

</#if>

<#-- ----------  BEGIN 字段循环遍历  ---------->

<#list table.fields as field>

    <#if field.keyFlag>

        <#assign keyPropertyName="${field.propertyName}"/>

    </#if>

 

    <#if field.comment!?length gt 0>

        <#if swagger2>

    @ApiModelProperty(value = "${field.comment}")

        <#else>

    /**

     * ${field.comment}

     */

        </#if>

    </#if>

    <#if field.keyFlag>

        <#-- 主键 -->

        <#if field.keyIdentityFlag>

    @TableId(value = "${field.annotationColumnName}", type = IdType.AUTO)

        <#elseif idType??>

    @TableId(value = "${field.annotationColumnName}", type = IdType.${idType})

        <#elseif field.convert>

    @TableId("${field.annotationColumnName}")

        </#if>

        <#-- 普通字段 -->

    <#elseif field.fill??>

    <#-- -----   存在字段填充设置   ----->

        <#if field.convert>

    @TableField(value = "${field.annotationColumnName}", fill = FieldFill.${field.fill})

        <#else>

    @TableField(fill = FieldFill.${field.fill})

        </#if>

    <#elseif field.convert>

    @TableField("${field.annotationColumnName}")

    </#if>

    <#-- 乐观锁注解 -->

    <#if (versionFieldName!"") == field.name>

    @Version

    </#if>

    <#-- 逻辑删除注解 -->

    <#if (logicDeleteFieldName!"") == field.name>

    @TableLogic

    </#if>

    private ${field.propertyType} ${field.propertyName};

</#list>

<#------------  END 字段循环遍历  ---------->

 

<#if !entityLombokModel>

    <#list table.fields as field>

        <#if field.propertyType == "boolean">

            <#assign getprefix="is"/>

        <#else>

            <#assign getprefix="get"/>

        </#if>

    public ${field.propertyType} ${getprefix}${field.capitalName}() {

        return ${field.propertyName};

    }

 

    <#if chainModel>

    public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {

    <#else>

    public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {

    </#if>

        this.${field.propertyName} = ${field.propertyName};

        <#if chainModel>

        return this;

        </#if>

    }

    </#list>

</#if>

 

<#if entityColumnConstant>

    <#list table.fields as field>

    public static final String ${field.name?upper_case} = "${field.name}";

 

    </#list>

</#if>

<#if activeRecord>

    @Override

    protected Serializable pkVal() {

    <#if keyPropertyName??>

        return this.${keyPropertyName};

    <#else>

        return null;

    </#if>

    }

 

</#if>

<#if !entityLombokModel>

    @Override

    public String toString() {

        return "${entity}{" +

    <#list table.fields as field>

        <#if field_index==0>

            "${field.propertyName}=" + ${field.propertyName} +

        <#else>

            ", ${field.propertyName}=" + ${field.propertyName} +

        </#if>

    </#list>

        "}";

    }

</#if>

}

로그인 후 복사

7.mybatisplus 템플릿——mapper

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

package ${package.Mapper};

 

import ${package.Entity}.${entity};

import ${superMapperClassPackage};

 

/**

 * @author ${author}

 * @date ${date}

 */

<#if kotlin>

interface ${table.mapperName} : ${superMapperClass}<${entity}>

<#else>

public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {

 

}

</#if>

로그인 후 복사

8.mybatisplus 템플릿——mybatisplusConfig

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

package ${cfg.packagePath}.globalconfig;

 

import com.baomidou.mybatisplus.annotation.DbType;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;

import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.transaction.annotation.EnableTransactionManagement;

 

/**

 * @author ${author}

 * @date ${date}

 */

@Configuration

@EnableTransactionManagement

public class MybatisPlusConfig {

 

    /**

     * @author fastrabbit

     * @description 获取分页插件

     * @date ${date}

     */

    @Bean

    public MybatisPlusInterceptor mybatisPlusInterceptor() {

        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));

        return interceptor;

    }

 

}

로그인 후 복사

9.mybatisplus 템플릿——result

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

package ${cfg.packagePath}.common;

 

import lombok.Data;

 

/**

 * @author ${author}

 * @date ${date}

 */

@Data

public class Result<T> {

 

    /**

     * 是否成功  默认为成功

     */

    private Boolean success = true;

 

    /**

     * 状态码  默认为200

     */

    private Integer code = 200;

 

    /**

     * 返回信息描述

     */

    private String message;

 

    /**

     * 返回数据

     */

    private T data;

 

    /**

     * 返回数据量

     */

    private Integer total;

 

}

로그인 후 복사

10.mybatisplus 템플릿 ——service

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

package ${package.Service};

 

import ${superServiceClassPackage};

import ${cfg.packagePath}.common.Result;

import ${package.Entity}.${entity};

 

import java.util.List;

 

/**

 * @author ${author}

 * @date ${date}

 */

<#if kotlin>

interface ${table.serviceName} : ${superServiceClass}<${entity}>

<#else>

public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {

 

    /**

     * @author fastrabbit

     * @description 根据id查询单个数据

     * @date ${date}

     */

    Result<${entity}> getById(${entity} ${entity?uncap_first});

 

    /**

     * @author fastrabbit

     * @description 根据查询条件查询分页数据

     * @date ${date}

     */

    Result<List<${entity}>> findListByPage(${entity} ${entity?uncap_first});

 

    /**

     * @author fastrabbit

     * @description 查询所有数据

     * @date ${date}

     */

    Result<List<${entity}>> getAll();

 

    /**

     * @author fastrabbit

     * @description 新增单个数据

     * @date ${date}

     */

    Result<Object> insert(${entity} ${entity?uncap_first});

 

    /**

    * @author fastrabbit

    * @description 修改单个数据

    * @date ${date}

    */

    Result<Object> update(${entity} ${entity?uncap_first});

 

    /**

     * @author fastrabbit

     * @description 删除单个数据

     * @date ${date}

     */

    Result<Object> delete(${entity} ${entity?uncap_first});

 

}

</#if>

로그인 후 복사

11.mybatisplus 템플릿 ——serviceImpl

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

package ${package.ServiceImpl};

 

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import ${cfg.packagePath}.common.Result;

import ${package.Entity}.${entity};

import ${package.Mapper}.${table.mapperName};

import ${package.Service}.${table.serviceName};

import ${superServiceImplClassPackage};

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

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

 

import java.util.List;

 

/**

 * @author ${author}

 * @date ${date}

 */

@Service

@Transactional(rollbackFor=Exception.class)

<#if kotlin>

open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} {

 

}

<#else>

public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {

 

    @Autowired

    private ${table.mapperName} ${table.mapperName?uncap_first};

 

    /**

     * @author fastrabbit

     * @description 根据id查询单个数据

     * @date ${date}

     */

    @Override

    public Result<${entity}> getById(Food food) {

 

        Result<${entity}> foodResult = new Result<>();

        foodResult.setData(foodMapper.selectById(food.getId()));

        return foodResult;

 

    }

 

    /**

     * @author fastrabbit

     * @description 根据查询条件查询分页数据

     * @date ${date}

     */

    @Override

    public Result<List<${entity}>> findListByPage(Food food) {

 

        Result<List<${entity}>> listResult = new Result<>();

        Page<${entity}> foodPage = new Page<>(food.getPage(), food.getRows());

        QueryWrapper<${entity}> foodQueryWrapper = new QueryWrapper<>();

        List<${entity}> records = foodMapper.selectPage(foodPage, foodQueryWrapper).getRecords();

        listResult.setData(records);

        listResult.setTotal(records.size());

        return listResult;

 

    }

 

    /**

     * @author fastrabbit

     * @description 查询所有数据

     * @date ${date}

     */

    @Override

    public Result<List<${entity}>> getAll() {

 

        Result<List<${entity}>> foodResult = new Result<>();

        List<${entity}> foods = foodMapper.selectList(null);

        foodResult.setData(foods);

        foodResult.setTotal(foods.size());

        return foodResult;

 

    }

 

    /**

     * @author fastrabbit

     * @description 新增单个数据

     * @date ${date}

     */

    @Override

    public Result<Object> insert(Food food) {

 

        Result<Object> objectResult = new Result<>();

        foodMapper.insert(food);

        return objectResult;

 

    }

 

    /**

     * @author fastrabbit

     * @description 修改单个数据

     * @date ${date}

     */

    @Override

    public Result<Object> update(Food food) {

 

        Result<Object> objectResult = new Result<>();

        foodMapper.updateById(food);

        return objectResult;

 

    }

 

    /**

     * @author fastrabbit

     * @description 删除单个数据

     * @date ${date}

     */

    @Override

    public Result<Object> delete(Food food) {

 

        Result<Object> objectResult = new Result<>();

        foodMapper.deleteById(food.getId());

        return objectResult;

 

    }

 

}

</#if>

로그인 후 복사

12.mybatisplus 템플릿 코드 생성기 ——CodeGenerator

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

package com.zengjx.project;

 

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;

import com.baomidou.mybatisplus.core.toolkit.StringPool;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import com.baomidou.mybatisplus.generator.AutoGenerator;

import com.baomidou.mybatisplus.generator.InjectionConfig;

import com.baomidou.mybatisplus.generator.config.*;

import com.baomidou.mybatisplus.generator.config.po.TableInfo;

import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

 

import java.io.File;

import java.util.*;

 

/**

 * @author fastrabbit

 * @date 2021/5/25 9:28

 */

public class CodeGenerator {

 

    /**

     * <p>

     * 读取控制台内容

     * </p>

     */

    public static String scanner(String tip) {

        Scanner scanner = new Scanner(System.in);

        StringBuilder help = new StringBuilder();

        help.append("请输入" + tip + ":");

        System.out.println(help.toString());

        if (scanner.hasNext()) {

            String ipt = scanner.next();

            if (StringUtils.isNotBlank(ipt)) {

                return ipt;

            }

        }

        throw new MybatisPlusException("请输入正确的" + tip + "!");

    }

 

    public static void main(String[] args) {

        // 代码生成器

        AutoGenerator mpg = new AutoGenerator();

 

        // 全局配置

        GlobalConfig gc = new GlobalConfig();

        // 获取到当前项目的根目录

        String projectPath = System.getProperty("user.dir");

        // 在指定的文件夹下生成文件的输出目录

        gc.setOutputDir(projectPath + "/src/main/java");

        // 设置类注释中的类的作者

        gc.setAuthor("fastrabbit");

        // 是否打开输出目录

        gc.setOpen(false);

        // 实体属性 Swagger2 注解

        gc.setSwagger2(true);

        // 开启activeRecord模式 开启后entity会继承Model类

        gc.setActiveRecord(false);

        // XML ResultMap: mapper.xml生成查询映射结果

        gc.setBaseResultMap(true);

        // 是否覆盖原来的文件

        gc.setFileOverride(false);

        mpg.setGlobalConfig(gc);

 

//======================================================================================================================

 

        // 数据源配置

        DataSourceConfig dsc = new DataSourceConfig();

        dsc.setUrl("jdbc:mysql://192.168.0.199:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8");

        // dsc.setSchemaName("public");

        dsc.setDriverName("com.mysql.cj.jdbc.Driver");

        dsc.setUsername("root");

        dsc.setPassword("123456");

        mpg.setDataSource(dsc);

 

//======================================================================================================================

 

        // 包配置

        PackageConfig pc = new PackageConfig();

        pc.setModuleName(scanner("模块名"));

        // 设置包的路径  该路径为 com.公司名.项目名

        String packagePath = "com.zengjx.project";

        pc.setParent(packagePath);

        mpg.setPackageInfo(pc);

 

//======================================================================================================================

 

        // 自定义配置

        InjectionConfig cfg = new InjectionConfig() {

            @Override

            public void initMap() {

                Map<String, Object> map = new HashMap<>();

                List<TableInfo> tableInfoList = this.getConfig().getTableInfoList();

                for (TableInfo tableInfo : tableInfoList) {

                    //项目包的路径 使用到的类有BaseQuery、MybatisPlusConfig、Result

                    map.put("packagePath", packagePath);

                }

                this.setMap(map);

            }

        };

 

//======================================================================================================================

 

        // 如果模板引擎是 freemarker

        String templatePath = "/templates/mapper.xml.ftl";

        // 如果模板引擎是 velocity

        // String templatePath = "/templates/mapper.xml.vm";

 

        // 自定义输出配置

        List<FileOutConfig> focList = new ArrayList<>();

        // 自定义配置会被优先输出  这是一个示例

        focList.add(new FileOutConfig(templatePath) {

            @Override

            public String outputFile(TableInfo tableInfo) {

                // 自定义输出文件名,如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!

                // 指定xml文件输出位置

                return projectPath + "/src/main/resources/com/zengjx/project/" + pc.getModuleName() + "/mapper"

                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;

            }

        });

 

        // 自定义controller的代码模板

        templatePath = "/templates/controller.java.ftl";

        // 自定义配置会被优先输出

        focList.add(new FileOutConfig(templatePath) {

            @Override

            public String outputFile(TableInfo tableInfo) {

                // 自定义输出文件名 + pc.getModuleName()

                String expand = projectPath + "/src/main/java/com/zengjx/project/" + pc.getModuleName() + "/" + "controller";

                return String.format((expand + File.separator + "%s" + ".java") , tableInfo.getControllerName());

            }

        });

 

        // 自定义entity的代码模板

        templatePath = "/templates/entity.java.ftl";

        // 自定义配置会被优先输出

        focList.add(new FileOutConfig(templatePath) {

            @Override

            public String outputFile(TableInfo tableInfo) {

                // 自定义输出文件名 + pc.getModuleName()

                String expand = projectPath + "/src/main/java/com/zengjx/project/" + pc.getModuleName() + "/" + "entity";

                return String.format((expand + File.separator + "%s" + ".java") , tableInfo.getEntityName());

            }

        });

 

        // 自定义service的代码模板

        templatePath = "/templates/service.java.ftl";

        // 自定义配置会被优先输出

        focList.add(new FileOutConfig(templatePath) {

            @Override

            public String outputFile(TableInfo tableInfo) {

                // 自定义输出文件名 + pc.getModuleName()

                String expand = projectPath + "/src/main/java/com/zengjx/project/" + pc.getModuleName() + "/" + "service";

                return String.format((expand + File.separator + "%s" + ".java") , tableInfo.getServiceName());

            }

        });

 

        // 自定义BaseQuery代码模板

        templatePath = "/templates/baseQuery.java.ftl";

        // 自定义配置会被优先输出

        focList.add(new FileOutConfig(templatePath) {

            @Override

            public String outputFile(TableInfo tableInfo) {

                // 自定义输出文件名 + pc.getModuleName()

                String expand = projectPath + "/src/main/java/com/zengjx/project/" + "common";

                return String.format((expand + File.separator + "%s" + ".java") , "BaseQuery");

            }

        });

 

        // 自定义Result代码模板

        templatePath = "/templates/result.java.ftl";

        // 自定义配置会被优先输出

        focList.add(new FileOutConfig(templatePath) {

            @Override

            public String outputFile(TableInfo tableInfo) {

                // 自定义输出文件名 + pc.getModuleName()

                String expand = projectPath + "/src/main/java/com/zengjx/project/" + "common";

                return String.format((expand + File.separator + "%s" + ".java") , "Result");

            }

        });

 

        // 自定义全局MybatisPlusConfig代码模板

        templatePath = "/templates/mybatisPlusConfig.java.ftl";

        // 自定义配置会被优先输出

        focList.add(new FileOutConfig(templatePath) {

            @Override

            public String outputFile(TableInfo tableInfo) {

                // 自定义输出文件名 + pc.getModuleName()

                String expand = projectPath + "/src/main/java/com/zengjx/project/" + "globalconfig";

                return String.format((expand + File.separator + "%s" + ".java") , "MybatisPlusConfig");

            }

        });

 

//======================================================================================================================

 

        cfg.setFileOutConfigList(focList);

        mpg.setCfg(cfg);

 

        // 配置模板

        TemplateConfig templateConfig = new TemplateConfig();

 

        // 配置自定义输出模板

        // 指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别

        // templateConfig.setEntity("templates/entity2.java");

        // templateConfig.setService();

        // templateConfig.setController();

 

        templateConfig.setXml(null);

        mpg.setTemplate(templateConfig);

 

//======================================================================================================================

 

        // 策略配置

        StrategyConfig strategy = new StrategyConfig();

        // 数据库表映射到实体的命名策略  下划线转驼峰命名

        strategy.setNaming(NamingStrategy.underline_to_camel);

        // 数据库表字段映射到实体的命名策略  下划线转驼峰命名

        strategy.setColumnNaming(NamingStrategy.underline_to_camel);

        // 设置entity继承的父类

        //strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");

        // 设置实体类是否为lombok模型

        strategy.setEntityLombokModel(true);

        // 设置controller为restful风格

        strategy.setRestControllerStyle(true);

        // 设置controller的公共父类

        //strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");

        // 设置entity公共父类中的公共字段  如果这里设置了那么生成的entity就不会去生成Id了

        //strategy.setSuperEntityColumns("id");

        // 给那些表创建文件

        strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));

        // 驼峰转连字符

        strategy.setControllerMappingHyphenStyle(true);

        // 设置表的前缀

        strategy.setTablePrefix(pc.getModuleName() + "_");

        // 将表的配置交给代码生成器

        mpg.setStrategy(strategy);

        // 创建模板引擎

        mpg.setTemplateEngine(new FreemarkerTemplateEngine());

        // 执行

        mpg.execute();

    }

 

}

로그인 후 복사

13.redis 구성 파일

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

package com.zengjx.project.globalconfig;

 

import com.fasterxml.jackson.annotation.JsonAutoDetect;

import com.fasterxml.jackson.annotation.JsonTypeInfo;

import com.fasterxml.jackson.annotation.PropertyAccessor;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;

import org.springframework.cache.annotation.CachingConfigurerSupport;

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.cache.RedisCacheWriter;

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.StringRedisSerializer;

 

/**

 * @author fastrabbit

 * @date 2021/6/9 9:55

 */

@Configuration

public class RedisConfig extends CachingConfigurerSupport {

 

    /**

     * @description: 将模板RedisTemplate<String, Object>中的key和value进行序列化

     * @param: RedisConnectionFactory

     * @return: RedisTemplate<String, Object>

     * @author: fastrabbit

     * @date: 2021/6/11 9:12

     */

    @Bean

    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {

 

        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<Object>(Object.class);

        ObjectMapper objectMapper = new ObjectMapper();

        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);

        serializer.setObjectMapper(objectMapper);

 

        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();

        redisTemplate.setConnectionFactory(redisConnectionFactory);

        redisTemplate.setKeySerializer(new StringRedisSerializer());

        redisTemplate.setValueSerializer(serializer);

        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        redisTemplate.setHashValueSerializer(serializer);

        redisTemplate.afterPropertiesSet();

 

        return redisTemplate;

 

    }

 

    /**

     * @description: 设置RedisCacheManager

     * @param: RedisTemplate

     * @return: RedisCacheManager

     * @author: fastrabbit

     * @date: 2021/6/11 9:12

     */

    @Bean

    public RedisCacheManager redisCacheManager(RedisTemplate redisTemplate) {

 

        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisTemplate.getConnectionFactory());

        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getValueSerializer()));

        return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);

 

    }

 

}

로그인 후 복사

14.redis 템플릿 몇 가지 일반적인 방법

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

package com.zengjx.project.redis.test;

 

import io.swagger.models.auth.In;

import org.junit.Test;

import org.junit.runner.RunWith;

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

import org.springframework.boot.test.context.SpringBootTest;

import org.springframework.data.redis.connection.DataType;

import org.springframework.data.redis.core.*;

import org.springframework.test.context.junit4.SpringRunner;

 

import java.util.*;

import java.util.concurrent.TimeUnit;

 

/**

 * @author fastrabbit

 * @date 2021/6/9 9:30

 */

@RunWith(SpringRunner.class)

@SpringBootTest

public class RedisTemplateTest {

 

    @Autowired

    private RedisTemplate<String, Object> redisTemplate;

 

    @Test

    public void stringRedisTemplateTest() {

 

        //保存:保存key和value

        redisTemplate.opsForValue().set("stringKey1", "stringKey1_value");

 

        //保存:保存key和value  如果Key存在则返回false  否则保存成功并返回true

        Boolean message1 = redisTemplate.opsForValue().setIfAbsent("stringKey1", "message1");

        System.out.println(message1);

 

        //保存:保存key和value并设置过期时间

        redisTemplate.opsForValue().set("stringKey2", "stringKey2_value", 20, TimeUnit.SECONDS);

 

        //保存:通过map的方式保存key和value

        HashMap<String, Object> hashMap1 = new HashMap<>();

        hashMap1.put("stringKeyHash1", "stringKeyHash1_value");

        hashMap1.put("stringKeyHash2", "stringKeyHash2_value");

        hashMap1.put("stringKeyHash3", "stringKeyHash3_value");

        redisTemplate.opsForValue().multiSet(hashMap1);

 

        //保存:通过map的方式保存key和valu  如果map集合中的所有key在redis中不存在则添加否则不做修改

        HashMap<String, Object> hashMap2 = new HashMap<>();

        hashMap2.put("stringKeyHash3", "stringKeyHash3_value");

        hashMap2.put("stringKeyHash4", "stringKeyHash4_value");

        hashMap2.put("stringKeyHash5", "stringKeyHash5_value");

        redisTemplate.opsForValue().multiSetIfAbsent(hashMap2);

 

        //修改:在原来key值对应的value新增字符串到末尾处

        redisTemplate.opsForValue().set("stringKey3", "stringKey3_value");

        redisTemplate.opsForValue().append("stringKey3", "+新增字符串");

 

        //修改:修改key对应的value值  使用覆盖的方式

        redisTemplate.opsForValue().set("stringKey4", "stringKey4_value");

        redisTemplate.opsForValue().set("stringKey4", "stringKey4_newValue");

 

        //修改:修改key的值

        redisTemplate.opsForValue().set("stringKey5", "stringKey5_value");

        redisTemplate.rename("stringKey5", "newStringKey5");

 

        //修改:修改key的值  如果存在则修改返回ture  否则报错:ERR no such key

        redisTemplate.opsForValue().set("stringKey6", "stringKey6_value");

        Boolean message2 = redisTemplate.renameIfAbsent("stringKey6", "newStringKey6");

        System.out.println(message2);

 

        //修改:修改key的value值并返回原来的value值

        redisTemplate.opsForValue().set("stringKey7", "stringKey7_value");

        String exchange = (String)redisTemplate.opsForValue().getAndSet("stringKey7", "newStringKey7_value");

        System.out.println(exchange);

 

        //查询:获取指定key对应的value值

        redisTemplate.opsForValue().set("stringKey8", "stringKey8_value");

        String stringKey8 = (String)redisTemplate.opsForValue().get("stringKey8");

        System.out.println(stringKey8);

 

        //查询:批量获取到key对应的value值  参数为Collection<String> keys

        ArrayList<String> arrayListKeys = new ArrayList<>();

        arrayListKeys.add("stringKey1");

        arrayListKeys.add("stringKey2");

        arrayListKeys.add("stringKey3");

        List<Object> arrayListValues = redisTemplate.opsForValue().multiGet(arrayListKeys);

        for (Object arrayListValue : arrayListValues) {

            System.out.println(arrayListValue);

        }

 

        //查询:获取指定Key的value值并设定截取长度

        redisTemplate.opsForValue().set("stringKey9", "stringKey9_value");

        String stringKey9Value = redisTemplate.opsForValue().get("stringKey9", 1, 5);

        System.out.println(stringKey9Value);

 

        //查询:获取指定key的过期时间

        redisTemplate.opsForValue().set("stringKey10", "stringKey10_value", 666, TimeUnit.SECONDS);

        Long stringKey10Expire = redisTemplate.getExpire("stringKey10", TimeUnit.SECONDS);

        System.out.println(stringKey10Expire);

 

        //查询:从redis中随机获取到一个key值

        String randomKey = redisTemplate.randomKey();

        System.out.println(randomKey);

 

        //查询:返回key的value的类型

        redisTemplate.opsForValue().set("stringKey11", "stringKey11_value");

        DataType stringKey11DataType = redisTemplate.type("stringKey11");

        System.out.println(stringKey11DataType);

 

        //查询:查询匹配的key值  *:匹配任意多个字符  ?:配置单个字符  []:配置括号内的某1个字符

        Set<String> allKeys = redisTemplate.keys("*");

        Set<String> somekeys = redisTemplate.keys("stringKey?");

        Set<String> otherKeys = redisTemplate.keys("stringKey[123]");

 

        //删除:删除单个的key和它的vlue

        redisTemplate.opsForValue().set("stringKey12", "stringKey12_value");

        Boolean deleteStringKey12 = redisTemplate.delete("stringKey12");

        System.out.println(deleteStringKey12);

 

        //删除:批量删除集合中的key值  返回删除了的数量

        redisTemplate.opsForValue().set("stringKey13", "stringKey13_value");

        redisTemplate.opsForValue().set("stringKey14", "stringKey14_value");

        redisTemplate.opsForValue().set("stringKey15", "stringKey15_value");

        ArrayList<String> arrayListDelete = new ArrayList<>();

        arrayListDelete.add("stringKey13");

        arrayListDelete.add("stringKey14");

        arrayListDelete.add("stringKey15");

        Long deleteArrayList = redisTemplate.delete(arrayListDelete);

        System.out.println(deleteArrayList);

 

        //其他:将key序列化为byte[]类型

        redisTemplate.opsForValue().set("stringKey16", "stringKey16_value");

        byte[] stringKey16ByteArray = redisTemplate.dump("stringKey16");

        System.out.println(stringKey16ByteArray);

 

        //其他:将key进行持久化保存

        redisTemplate.opsForValue().set("stringKey17", "stringKey17_value");

        Boolean stringKey17Persist = redisTemplate.persist("stringKey17");

        System.out.println(stringKey17Persist);

 

        //其他:将当前库中的key移动到指定的库中

        redisTemplate.opsForValue().set("stringKey18", "stringKey18_value");

        Boolean stringKey18Move = redisTemplate.move("stringKey18", 1);

        System.out.println(stringKey18Move);

 

        //其他:获取到key的value字符串长度

        redisTemplate.opsForValue().set("stringKey19", "stringKey19_value");

        Long stringKey19Size = redisTemplate.opsForValue().size("stringKey19");

        System.out.println(stringKey19Size);

 

        //其他:查看是否存在指定的key

        Boolean hasStringKey19 = redisTemplate.hasKey("stringKey19");

        System.out.println(hasStringKey19);

 

    }

 

    @Test

    public void hashRedisTemplateTest() {

 

        //保存:保存一个hashMap

        redisTemplate.opsForHash().put("hashKey1", "field1", "field1_value");

 

        //保存:保存一个hashMap  仅当field不存在的时候才保存成功

        Boolean putIfAbsentField = redisTemplate.opsForHash().putIfAbsent("hashKey1", "field1", "field1_value_attach");

        System.out.println(putIfAbsentField);

 

        //保存:通过map的形式添加键值对

        HashMap<String, Object> hashMap3 = new HashMap<>();

        hashMap3.put("field2", "field2_value");

        hashMap3.put("field2_attach1", "field2_attach1_value");

        hashMap3.put("field2_attach2", "field2_attach2_value");

        redisTemplate.opsForHash().putAll("hashKey2", hashMap3);

 

        //修改:

        redisTemplate.opsForHash().put("hashKey3", "field3", "field3_value");

        redisTemplate.opsForHash().put("hashKey3", "field3", "newField3_value");

 

        //查询:获取指定hashKey、field的value值

        redisTemplate.opsForHash().put("hashKey4", "field4", "field4_value");

        String getSpecifyValue = (String)redisTemplate.opsForHash().get("hashKey4", "field4");

        System.out.println(getSpecifyValue);

 

        //查询:获取指定hashKey的map值

        redisTemplate.opsForHash().put("hashKey5", "field5", "field5_value");

        Map<Object, Object> getSpecifyMap = redisTemplate.opsForHash().entries("hashKey5");

        for (Object o : getSpecifyMap.keySet()) {

            System.out.println(o);

            System.out.println(getSpecifyMap.get(o));

        }

 

        //查询:获取指定hashkey中的所有field字段

        HashMap<String, Object> hashMap4 = new HashMap<>();

        hashMap4.put("field6", "field6_value");

        hashMap4.put("field6_attach1", "field6_attach1_value");

        hashMap4.put("field6_attach2", "field6_attach2_value");

        redisTemplate.opsForHash().putAll("hashKey6", hashMap4);

        Set<Object> getSpecifySet = redisTemplate.opsForHash().keys("hashKey6");

        for (Object o : getSpecifySet) {

            System.out.println(o);

        }

 

        //查询:获取到指定hashKey的field的数量

        HashMap<String, Object> hashMap5 = new HashMap<>();

        hashMap5.put("field7", "fiele7_value");

        hashMap5.put("field7_attach1", "fiele7_attach1_value");

        hashMap5.put("field7_attach2", "fiele7_attach2_value");

        redisTemplate.opsForHash().putAll("hashKey7", hashMap5);

        Long hashKey7Size = redisTemplate.opsForHash().size("hashKey7");

        System.out.println(hashKey7Size);

 

        //查询:获取指定hashKey的所有field的value值

        HashMap<String, Object> hashMap6 = new HashMap<>();

        hashMap6.put("field8", "field8_value");

        hashMap6.put("field8_attach1", "field8_attach1_value");

        hashMap6.put("field8_attach2", "field8_attach2_value");

        redisTemplate.opsForHash().putAll("hashKey8", hashMap6);

        List<Object> hashKey8Values = redisTemplate.opsForHash().values("hashKey8");

        for (Object hashKey8Value : hashKey8Values) {

            System.out.println(hashKey8Value);

        }

 

    }

 

    @Test

    public void listRedisTemplateTest() {

 

        //保存:存储在key链表的右边  并返回长度

        Long listKey1Length = redisTemplate.opsForList().rightPush("listKey1", "listKey1_value");

        System.out.println(listKey1Length);

 

        //保存:存储多个值在list的右边  参数为Collect<T>  参数泛型需要和设置的模板的泛型一致,不然保存的是数组而不是数组元素

        redisTemplate.opsForList().rightPush("listKey2", "listKey2_value");

        ArrayList<Object> arrayList1 = new ArrayList<>();

        arrayList1.add("listKey2_attach1_value");

        arrayList1.add("listKey2_attach2_value");

        arrayList1.add("listKey2_attach3_value");

        Long listKey2Length1 = redisTemplate.opsForList().rightPushAll("listKey2", "listKey2_attach1_value", "listKey2_attach2_value", "listKey2_attach3_value");

        Long listKey2Length2 = redisTemplate.opsForList().rightPushAll("listKey2", arrayList1);

        System.out.println(listKey2Length1);

        System.out.println(listKey2Length2);

 

        //保存:存储在key连表的左边  并返回长度

        Long listKey3Length1 = redisTemplate.opsForList().leftPush("listKey3", "listKey3_value");

        Long listKey3Length2 = redisTemplate.opsForList().leftPush("listKey3", "listKey3_attach1_value");

        System.out.println(listKey3Length1);

        System.out.println(listKey3Length2);

 

        //保存:存储多个值在list的左边  参数为collect<T>

        redisTemplate.opsForList().leftPush("listKey4", "listKey4_value");

        ArrayList<Object> arrayList2 = new ArrayList<>();

        arrayList2.add("listKey4_attach1_value");

        arrayList2.add("listKey4_attach2_value");

        arrayList2.add("listKey4_attach3_value");

        Long listKey4Length1 = redisTemplate.opsForList().leftPushAll("listKey4", "listKey4_attach1_value", "listKey4_attach2_value", "listKey4_attach3_value");

        Long listKey4Length2 = redisTemplate.opsForList().leftPushAll("listKey4", arrayList2);

        System.out.println(listKey4Length1);

        System.out.println(listKey4Length2);

 

        //保存:在指定的key中的pivot(key的value)的前面添加值  如果存在则添加  否则不添加并返回-1

        redisTemplate.opsForList().leftPush("listKey5", "listKey5_value");

        Long listKey5Length1 = redisTemplate.opsForList().leftPush("listKey5", "nothing", "listKey5_attach1_value");

        System.out.println(listKey5Length1);

 

        //保存:在指定的key中的pivot(key的value)的后面添加值  如果存在则添加  否则不添加并返回-1

        redisTemplate.opsForList().rightPush("listKey6", "listKey6_value");

        Long listKey6Length1 = redisTemplate.opsForList().rightPush("listKey6", "nothing", "listKey6_attach1_value");

        System.out.println(listKey6Length1);

 

        //保存:只有当链表存在的时候才加入  否则返回0

        Long nothing1 = redisTemplate.opsForList().leftPushIfPresent("nothing", "test");

        Long nothing2 = redisTemplate.opsForList().rightPushIfPresent("nothing", "test");

        System.out.println(nothing1);

        System.out.println(nothing2);

 

        //修改:修改指定索引处的值  如果索引大于链表长度或报错ERR index out of range

        redisTemplate.opsForList().rightPush("listKey7", "listKey7_value");

        redisTemplate.opsForList().set("listKey7", 0, "listKey7_attach1_value");

 

        //修改:将链表key进行剪切,从指定的索引处开始到指定索引处结束

        redisTemplate.opsForList().rightPushAll("listKey7", "listKey7_value", "listKey7_attach1_value", "listKey7_attach2_value");

        redisTemplate.opsForList().trim("listKey7", 0, 1);

 

        //查询:获取指定key和索引处的元素

        redisTemplate.opsForList().rightPushAll("listKey8", "listKey8_value", "listKey8_attach1_value", "listKey8_attach2_value");

        String listKey8IndexValues = (String)redisTemplate.opsForList().index("listKey8", 0);

        System.out.println(listKey8IndexValues);

 

        //查询:获取指定key和范围的元素集合 -1表示返回所有

        redisTemplate.opsForList().rightPushAll("listKey9", "listKey9_value", "listKey9_attach1_value", "listKey9_attach2_value");

        List<Object> listKey9RangeValues = redisTemplate.opsForList().range("listKey9", 0, 1);

        for (Object listKey9RangeValue : listKey9RangeValues) {

            System.out.println(listKey9RangeValue);

        }

 

        //删除:移除链表左边的第一个元素并获取到它的value值(如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止)可以设置超时时间

        redisTemplate.opsForList().rightPushAll("listKey10", "listKey10_value", "listKey10_attach1_value", "listKey10_attach2_value");

        Object listKey10PopValue = redisTemplate.opsForList().leftPop("listKey10", 10, TimeUnit.SECONDS);

        System.out.println(listKey10PopValue);

 

        //删除:移除链表右边的第一个元素并获取到它的value值(如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止)可以设置超时时间

        redisTemplate.opsForList().rightPushAll("listKey11", "listKey11_value", "listKey11_attach1_value", "listKey11_attach2_value");

        Object listKey11PopValue = redisTemplate.opsForList().rightPop("listKey11", 10, TimeUnit.SECONDS);

        System.out.println(listKey11PopValue);

 

        //删除:将一个链表的右边的第一个元素弹出放到另一个链表的左边

        redisTemplate.opsForList().rightPushAll("listKey12", "listKey12_value", "listKey12_attach1_value", "listKey12_attach2_value");

        redisTemplate.opsForList().rightPushAll("listKey13", "listKey13_value", "listKey13_attach1_value", "listKey13_attach2_value");

        Object rightPopAndLeftPushValue = redisTemplate.opsForList().rightPopAndLeftPush("listKey12", "listKey13", 10, TimeUnit.SECONDS);

        System.out.println(rightPopAndLeftPushValue);

 

        //删除:将链表中值等于value的元素删除(index=0, 删除所有值等于value的元素; index>0, 从头部开始删除第一个值等于value的元素; index<0, 从尾部开始删除第一个值等于value的元素)

        redisTemplate.opsForList().rightPushAll("listKey14", "listKey14_value", "listKey14_attach1_value", "listKey14_attach2_value");

        redisTemplate.opsForList().rightPushAll("listKey15", "listKey15_value", "listKey15_attach1_value", "listKey15_attach2_value");

        redisTemplate.opsForList().rightPushAll("listKey16", "listKey16_value", "listKey16_attach1_value", "listKey16_attach2_value");

        Long listKey14Remove = redisTemplate.opsForList().remove("listKey14", 0, "listKey14_value");

        Long listKey15Remove = redisTemplate.opsForList().remove("listKey15", 2, "listKey15_value");

        Long listKey16Remove = redisTemplate.opsForList().remove("listKey16", -3, "listKey16_value");

        System.out.println(listKey14Remove);

        System.out.println(listKey15Remove);

        System.out.println(listKey16Remove);

 

        //其他:获取到指定的key的list的长度

        redisTemplate.opsForList().rightPushAll("listKey17", "listKey17_value", "listKey17_attach1_value", "listKey17_attach2_value");

        Long listKey17Size = redisTemplate.opsForList().size("listKey17");

        System.out.println(listKey17Size);

 

    }

 

    @Test

    public void setRedisTemplateTest() {

 

        //保存:保存一个元素

        Long setKey1Length1 = redisTemplate.opsForSet().add("setKey1", "setKey1_value");

        System.out.println(setKey1Length1);

 

        //保存:批量添加元素  好像不能使用set、list集合来批量添加

        Long setKey2Length1 = redisTemplate.opsForSet().add("setKey2", "setKey2_value", "setKey2_attach1_value", "setKey2_attach2_value");

        System.out.println(setKey2Length1);

 

        //修改:没有找到修改value值的方法  可以通过先删除再保存的方式进行修改

 

        //查询:获取指定集合中的所有元素

        redisTemplate.opsForSet().add("setKey3", "setKey3_value", "setKey3_attach1_value", "setKey3_attach2_value");

        Set<Object> setKey3Values = redisTemplate.opsForSet().members("setKey3");

        for (Object setKey3Value : setKey3Values) {

            System.out.println(setKey3Value);

        }

 

        //查询:随机获取到集合中的count个元素

        redisTemplate.opsForSet().add("setKey4", "setKey4_value", "setKey4_attach1_value", "setKey4_attach2_value");

        List<Object> setKey4Values = redisTemplate.opsForSet().randomMembers("setKey4", 2);

        for (Object setKey4Value : setKey4Values) {

            System.out.println(setKey4Value);

        }

 

        //查询:获取到两个集合的交集

        redisTemplate.opsForSet().add("setKey5", "setKey5_value", "setKey5_attach1_value", "setKey5_setKey6_value");

        redisTemplate.opsForSet().add("setKey6", "setKey6_value", "setKey6_attach1_value", "setKey5_setKey6_value");

        Set<Object> set5AndSet6intersect = redisTemplate.opsForSet().intersect("setKey5", "setKey6");

        for (Object o : set5AndSet6intersect) {

            System.out.println(o);

        }

 

        //查询:获取多个集合的交集

        ArrayList<String> arrayList1 = new ArrayList<>();

        redisTemplate.opsForSet().add("setKey7", "setKey7_value", "setKey7_attach1_value", "setKey7_setKey8_setKey9_value");

        redisTemplate.opsForSet().add("setKey8", "setKey8_value", "setKey8_attach1_value", "setKey7_setKey8_setKey9_value");

        redisTemplate.opsForSet().add("setKey9", "setKey9_value", "setKey9_attach1_value", "setKey7_setKey8_setKey9_value");

        arrayList1.add("setKey8");

        arrayList1.add("setKey9");

        Set<Object> setKey7AndSet8AndSet9Intersect = redisTemplate.opsForSet().intersect("setKey7", arrayList1);

        for (Object o : setKey7AndSet8AndSet9Intersect) {

            System.out.println(o);

        }

 

        //查询:将一个集合和一个或者多个集合的交集存储到另一个集合中

        ArrayList<String> arrayList2 = new ArrayList<>();

        redisTemplate.opsForSet().add("setKey10", "setKey10_value", "setKey10_attach1_value", "setKey10_setKey11_setKey12_value");

        redisTemplate.opsForSet().add("setKey11", "setKey11_value", "setKey11_attach1_value", "setKey10_setKey11_setKey12_value");

        redisTemplate.opsForSet().add("setKey12", "setKey12_value", "setKey12_attach1_value", "setKey10_setKey11_setKey12_value");

        arrayList2.add("setKey11");

        arrayList2.add("setKey12");

        redisTemplate.opsForSet().intersectAndStore("setKey10", arrayList2, "setKey13");

 

        //查询:获取一个和另一个或者一个和多个集合的并集

        ArrayList<String> arrayList3 = new ArrayList<>();

        redisTemplate.opsForSet().add("setKey14", "setKey14_value", "setKey14_attach1_value", "setKey14_setKey15_setKey16_value");

        redisTemplate.opsForSet().add("setKey15", "setKey15_value", "setKey15_attach1_value", "setKey14_setKey15_setKey16_value");

        redisTemplate.opsForSet().add("setKey16", "setKey16_value", "setKey16_attach1_value", "setKey14_setKey15_setKey16_value");

        arrayList3.add("setKey15");

        arrayList3.add("setKey16");

        Set<Object> setKey14AndSet15AndSet16Union = redisTemplate.opsForSet().union("setKey14", arrayList3);

        for (Object o : setKey14AndSet15AndSet16Union) {

            System.out.println(o);

        }

        //查询:获取一个和另一个或者一个和多个集合的并集  并将集合存储在指定Key的reids中  并返回集合长度

        Long setKey14AndSet15AndSet16Length = redisTemplate.opsForSet().unionAndStore("setKey14", arrayList3, "setKey17");

        System.out.println(setKey14AndSet15AndSet16Length);

 

        //查询:获取一个和另一个或者一个和多个集合的差集  就是第一个集合和其他集合独有的元素提取出来为一个新的集合

        ArrayList<String> arrayList4 = new ArrayList<>();

        redisTemplate.opsForSet().add("setKey18", "setKey18_value", "setKey18_attach1_value", "setKey18_setKey19_setKey20_value");

        redisTemplate.opsForSet().add("setKey19", "setKey19_value", "setKey19_attach1_value", "setKey18_setKey19_setKey20_value");

        redisTemplate.opsForSet().add("setKey20", "setKey20_value", "setKey20_attach1_value", "setKey18_setKey19_setKey20_value");

        arrayList4.add("setKey19");

        arrayList4.add("setKey20");

        Set<Object> setKey18AndSet19AndSet20Difference = redisTemplate.opsForSet().difference("setKey18", arrayList4);

        for (Object o : setKey18AndSet19AndSet20Difference) {

            System.out.println(o);

        }

        //查询:获取一个和另一个或者一个和多个集合的差集  并将集合设置到指定key的redis中  并返回集合长度

        Long setKey18AndSet19AndSet20Length = redisTemplate.opsForSet().differenceAndStore("setKey18", arrayList4, "setKey21");

        System.out.println(setKey18AndSet19AndSet20Length);

 

        //查询:随机获取一个集合中的元素

        redisTemplate.opsForSet().add("setKey22", "setKey22_value", "setKey22_attach1_value", "setKey22_attach2_value");

        String setKey22RandomValues = (String)redisTemplate.opsForSet().randomMember("setKey22");

        System.out.println(setKey22RandomValues);

 

        //查询:获取集合中的所有元素

        redisTemplate.opsForSet().add("setKey23", "setKey23_value", "setKey23_attach1_value", "setKey23_attach2_value");

        Set<Object> setKey23Values = redisTemplate.opsForSet().members("setKey23");

        for (Object setKey23Value : setKey23Values) {

            System.out.println(setKey23Value);

        }

 

        //删除:移除指定Key中的value元素  并返回集合长度

        redisTemplate.opsForSet().add("setKey24", "setKey24_value", "setKey24_attach1_value", "setKey24_attach2_value");

        Long setKey24Length = redisTemplate.opsForSet().remove("setKey24", "setKey24_attach2_value");

        System.out.println(setKey24Length);

 

        //删除:随机删除指定key中的一个元素并返回

        redisTemplate.opsForSet().add("setKey25", "setKey25_value", "setKey25_attach1_value", "setKey25_attach2_value");

        Object setKey25Value = redisTemplate.opsForSet().pop("setKey25");

        System.out.println(setKey25Value);

 

        //其他:获取集合的大小

        redisTemplate.opsForSet().add("setKey26", "setKey26_value", "setKey26_attach1_value", "setKey26_attach2_value");

        Long setKey26Length = redisTemplate.opsForSet().size("setKey26");

        System.out.println(setKey26Length);

 

    }

 

    @Test

    public void zSetRedisTemplateTest() {

 

        //保存:保存一个一个元素到集合中  第三个参数score为排序的权值  权值越小排序越前(左)

        Boolean zSetKey1 = redisTemplate.opsForZSet().add("zSetKey1", "zSetKey1_value", 1);

        System.out.println(zSetKey1);

 

        //修改:给指定的key的value的score增加值  原来的score+新增值

        redisTemplate.opsForZSet().add("zSetKey2", "zSetKey2_value", 1);

        Double zSetKey2Score = redisTemplate.opsForZSet().incrementScore("zSetKey2", "zSetKey2_value", 5);

        System.out.println(zSetKey2Score);

 

        //查询:返回元素在集合中的排名

        redisTemplate.opsForZSet().add("zSetKey3", "zSetKey3_value", 1);

        redisTemplate.opsForZSet().add("zSetKey3", "zSetKey3_attach1_value", 2);

        redisTemplate.opsForZSet().add("zSetKey3", "zSetKey3_attach2_value", 3);

        Long zSetKey3Rank = redisTemplate.opsForZSet().rank("zSetKey3", "zSetKey3_attach2_value");

        System.out.println(zSetKey3Rank);

 

        //查询:获取集合集合给定区间的元素  -1表示查询所有

        DefaultTypedTuple<Object> objectDefaultTypedTuple1 = new DefaultTypedTuple<Object>("zSetKey4_value", 1d);

        DefaultTypedTuple<Object> objectDefaultTypedTuple2 = new DefaultTypedTuple<Object>("zSetKey4_attach1_value", 2d);

        DefaultTypedTuple<Object> objectDefaultTypedTuple3 = new DefaultTypedTuple<Object>("zSetKey4_attach2_value", 3d);

        Set<ZSetOperations.TypedTuple<Object>> typedTuples = new HashSet<>();

        typedTuples.add(objectDefaultTypedTuple1);

        typedTuples.add(objectDefaultTypedTuple2);

        typedTuples.add(objectDefaultTypedTuple3);

        redisTemplate.opsForZSet().add("zSetKey4", typedTuples);

        Set<ZSetOperations.TypedTuple<Object>> zSetKey4 = redisTemplate.opsForZSet().reverseRangeWithScores("zSetKey4", 1, 2);

        for (ZSetOperations.TypedTuple<Object> objectTypedTuple : zSetKey4) {

            Double score = objectTypedTuple.getScore();

            Object value = objectTypedTuple.getValue();

            System.out.println(value);

            System.out.println(score);

        }

        //查询:按照score值进行  结果按照score从小到大进行排序

        Set<ZSetOperations.TypedTuple<Object>> zSetKey41 = redisTemplate.opsForZSet().reverseRangeWithScores("zSetKey4", 1, 2);

        for (ZSetOperations.TypedTuple<Object> objectTypedTuple : zSetKey41) {

            Double score = objectTypedTuple.getScore();

            Object value = objectTypedTuple.getValue();

            System.out.println(score);

            System.out.println(value);

        }

        //查询key对应的value值在集合中的排名

        Long zSetKey4ValueRank = redisTemplate.opsForZSet().reverseRank("zSetKey4", "zSetKey4_attach2_value");

        System.out.println(zSetKey4ValueRank);

        //获取集合的大小

        Long zSetKey4Length2 = redisTemplate.opsForZSet().size("zSetKey4");

        System.out.println(zSetKey4Length2);

        //获取指定key和value中的score值

        Double score = redisTemplate.opsForZSet().score("zSetKey4", "zSetKey4_value");

        System.out.println(score);

         

        //删除指定key的指定value值  并返回删除元素的个数

        redisTemplate.opsForZSet().add("zSetKey5", "zSetKey5_value", 1);

        redisTemplate.opsForZSet().add("zSetKey5", "zSetKey5_attach1_value", 2);

        redisTemplate.opsForZSet().add("zSetKey5", "zSetKey5_attach2_value", 3);

        Long zSetKey5Length1 = redisTemplate.opsForZSet().remove("zSetKey5", "zSetKey5_value");

        System.out.println(zSetKey5Length1);

 

    }

 

    @Test

    public void emptyRedis() {

 

        Set<String> keys = redisTemplate.keys("*");

        redisTemplate.delete(keys);

 

    }

 

}

로그인 후 복사

15 .사용 방법 redis

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

package com.zengjx.project.annotation.service.impl;

 

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.zengjx.project.common.Result;

import com.zengjx.project.annotation.entity.Food;

import com.zengjx.project.annotation.mapper.FoodMapper;

import com.zengjx.project.annotation.service.IFoodService;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

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

import org.springframework.cache.annotation.CacheEvict;

import org.springframework.cache.annotation.CachePut;

import org.springframework.cache.annotation.Cacheable;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

 

import java.util.List;

 

/**

 * @author fastrabbit

 * @date 2021-06-11

 */

@Service

@Transactional(rollbackFor=Exception.class)

public class FoodServiceImpl extends ServiceImpl<FoodMapper, Food> implements IFoodService {

 

    @Autowired

    private FoodMapper foodMapper;

 

    @Autowired

    private IFoodService foodService;

 

    /**

     * @author fastrabbit

     * @description 根据id查询单个数据  将查询到的数据放入到redis缓存中,如果根据key值能够在redis中找到则直接返回redis中的数据不执行代码  condition为缓存条件

     * @date 2021-06-11

     */

    @Override

    @Cacheable(value = "PROJECT:ANNOTATION", key = "&#39;FOOD:&#39;+#food.id", condition = "#food.id>0")

    public Result<Food> getById(Food food) {

 

        Result<Food> foodResult = new Result<>();

        foodResult.setData(foodMapper.selectById(food.getId()));

        return foodResult;

 

    }

 

    /**

     * @author fastrabbit

     * @description 根据查询条件查询分页数据  将查询到的数据放入到redis缓存中,如果根据key值能够在redis中找到则直接返回redis中的数据不执行代码  condition为缓存条件

     * @date 2021-06-11

     */

    @Override

    @Cacheable(value = "PROJECT:ANNOTATION", key = "&#39;FOOD:&#39;+#food.page+&#39;_&#39;+#food.rows", condition = "#food.page>0 and #food.rows>=10")

    public Result<List<Food>> findListByPage(Food food) {

 

        Result<List<Food>> listResult = new Result<>();

        Page<Food> foodPage = new Page<>(food.getPage(), food.getRows());

        QueryWrapper<Food> foodQueryWrapper = new QueryWrapper<>();

        List<Food> records = foodMapper.selectPage(foodPage, foodQueryWrapper).getRecords();

        listResult.setData(records);

        listResult.setTotal(records.size());

        return listResult;

 

    }

 

    /**

     * @author fastrabbit

     * @description 查询所有数据  将查询到的数据放入到redis缓存中,如果根据key值能够在redis中找到则直接返回redis中的数据不执行代码

     * @date 2021-06-11

     */

    @Override

    @Cacheable(value = "PROJECT:ANNOTATION", key = "&#39;FOOD:&#39;+&#39;ALL&#39;")

    public Result<List<Food>> getAll() {

 

        Result<List<Food>> foodResult = new Result<>();

        List<Food> foods = foodMapper.selectList(null);

        foodResult.setData(foods);

        foodResult.setTotal(foods.size());

        return foodResult;

 

    }

 

    /**

     * @author fastrabbit

     * @description 新增单个数据

     * @date 2021-06-11

     */

    @Override

    public Result<Object> insert(Food food) {

 

        Result<Object> objectResult = new Result<>();

        foodMapper.insert(food);

        // 通过调用上面的getById方法将新增的数据添加到redis中

        // 因为redis注解存储的方式使用的是spring的aop动态代理所以通过注入自己的方式来使用代理类中的方法

        foodService.getById(food);

        return objectResult;

 

    }

 

    /**

     * @author fastrabbit

     * @description 修改单个数据

     * @date 2021-06-11

     */

    @Override

    public Result<Object> update(Food food) {

 

        Result<Object> objectResult = new Result<>();

        foodMapper.updateById(food);

        // 通过调用下面的redisUpdate方法将存储在redis中的数据进行更新

        // 因为redis注解存储的方式使用的是spring的aop动态代理所以通过注入自己的方式来使用代理类中的方法

        Result<Food> byId = foodService.redisUpdate(food);

        Food data = byId.getData();

        System.out.println(data);

        return objectResult;

 

    }

 

    /**

     * @author fastrabbit

     * @Description 修改redis缓存中的数据  @CachePut注解:一定会执行代码然后将返回数据存放在redis中,保证数据库和redis中的数据一致性

     * @Date 13:38 2021/6/11

     */

    @Override

    @CachePut(value = "PROJECT:ANNOTATION", key = "&#39;FOOD:&#39;+#food.id", condition = "#food.id>0")

    public Result<Food> redisUpdate(Food food) {

 

        Result<Food> foodResult = new Result<>();

        foodResult.setData(foodMapper.selectById(food.getId()));

        return foodResult;

 

    }

 

    /**

     * @author fastrabbit

     * @description 删除单个数据  @CacheEvict:当执行到该方法时会根据key将redis中的数据进行删除,具有多项配置

     * @date 2021-06-11

     */

    @Override

    @CacheEvict(value = "PROJECT:ANNOTATION", key = "&#39;FOOD:&#39;+#food.id", condition = "#food.id>0")

    public Result<Object> delete(Food food) {

 

        Result<Object> objectResult = new Result<>();

        foodMapper.deleteById(food.getId());

        return objectResult;

 

    }

 

}

로그인 후 복사
운영을 위한 몇 가지 주석

위 내용은 springboot+mybatisplus+redis 데모 구현 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

<gum> : Bubble Gum Simulator Infinity- 로얄 키를 얻고 사용하는 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
Nordhold : Fusion System, 설명
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora : 마녀 트리의 속삭임 - Grappling Hook 잠금 해제 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Redis 클러스터 모드를 구축하는 방법 Redis 클러스터 모드를 구축하는 방법 Apr 10, 2025 pm 10:15 PM

Redis Cluster Mode는 Sharding을 통해 Redis 인스턴스를 여러 서버에 배포하여 확장 성 및 가용성을 향상시킵니다. 시공 단계는 다음과 같습니다. 포트가 다른 홀수 redis 인스턴스를 만듭니다. 3 개의 센티넬 인스턴스를 만들고, Redis 인스턴스 및 장애 조치를 모니터링합니다. Sentinel 구성 파일 구성, Redis 인스턴스 정보 및 장애 조치 설정 모니터링 추가; Redis 인스턴스 구성 파일 구성, 클러스터 모드 활성화 및 클러스터 정보 파일 경로를 지정합니다. 각 redis 인스턴스의 정보를 포함하는 Nodes.conf 파일을 작성합니다. 클러스터를 시작하고 Create 명령을 실행하여 클러스터를 작성하고 복제본 수를 지정하십시오. 클러스터에 로그인하여 클러스터 정보 명령을 실행하여 클러스터 상태를 확인하십시오. 만들다

Redis 데이터를 지우는 방법 Redis 데이터를 지우는 방법 Apr 10, 2025 pm 10:06 PM

Redis 데이터를 지우는 방법 : Flushall 명령을 사용하여 모든 키 값을 지우십시오. FlushDB 명령을 사용하여 현재 선택한 데이터베이스의 키 값을 지우십시오. 선택을 사용하여 데이터베이스를 전환 한 다음 FlushDB를 사용하여 여러 데이터베이스를 지우십시오. del 명령을 사용하여 특정 키를 삭제하십시오. Redis-Cli 도구를 사용하여 데이터를 지우십시오.

Redis 대기열을 읽는 방법 Redis 대기열을 읽는 방법 Apr 10, 2025 pm 10:12 PM

Redis의 대기열을 읽으려면 대기열 이름을 얻고 LPOP 명령을 사용하여 요소를 읽고 빈 큐를 처리해야합니다. 특정 단계는 다음과 같습니다. 대기열 이름 가져 오기 : "큐 :"와 같은 "대기열 : my-queue"의 접두사로 이름을 지정하십시오. LPOP 명령을 사용하십시오. 빈 대기열 처리 : 대기열이 비어 있으면 LPOP이 NIL을 반환하고 요소를 읽기 전에 대기열이 존재하는지 확인할 수 있습니다.

Centos redis에서 lua 스크립트 실행 시간을 구성하는 방법 Centos redis에서 lua 스크립트 실행 시간을 구성하는 방법 Apr 14, 2025 pm 02:12 PM

CentOS 시스템에서는 Redis 구성 파일을 수정하거나 Redis 명령을 사용하여 악의적 인 스크립트가 너무 많은 리소스를 소비하지 못하게하여 LUA 스크립트의 실행 시간을 제한 할 수 있습니다. 방법 1 : Redis 구성 파일을 수정하고 Redis 구성 파일을 찾으십시오. Redis 구성 파일은 일반적으로 /etc/redis/redis.conf에 있습니다. 구성 파일 편집 : 텍스트 편집기 (예 : VI 또는 Nano)를 사용하여 구성 파일을 엽니 다. Sudovi/etc/redis/redis.conf LUA 스크립트 실행 시간 제한을 설정 : 구성 파일에서 다음 줄을 추가 또는 수정하여 LUA 스크립트의 최대 실행 시간을 설정하십시오 (Unit : Milliseconds).

Redis 명령 줄을 사용하는 방법 Redis 명령 줄을 사용하는 방법 Apr 10, 2025 pm 10:18 PM

Redis Command Line 도구 (Redis-Cli)를 사용하여 다음 단계를 통해 Redis를 관리하고 작동하십시오. 서버에 연결하고 주소와 포트를 지정하십시오. 명령 이름과 매개 변수를 사용하여 서버에 명령을 보냅니다. 도움말 명령을 사용하여 특정 명령에 대한 도움말 정보를 봅니다. 종금 명령을 사용하여 명령 줄 도구를 종료하십시오.

Redis 카운터를 구현하는 방법 Redis 카운터를 구현하는 방법 Apr 10, 2025 pm 10:21 PM

Redis Counter는 Redis Key-Value Pair 스토리지를 사용하여 다음 단계를 포함하여 계산 작업을 구현하는 메커니즘입니다. 카운터 키 생성, 카운트 증가, 카운트 감소, 카운트 재설정 및 카운트 얻기. Redis 카운터의 장점에는 빠른 속도, 높은 동시성, 내구성 및 단순성 및 사용 편의성이 포함됩니다. 사용자 액세스 계산, 실시간 메트릭 추적, 게임 점수 및 순위 및 주문 처리 계산과 같은 시나리오에서 사용할 수 있습니다.

Redis 만료 정책을 설정하는 방법 Redis 만료 정책을 설정하는 방법 Apr 10, 2025 pm 10:03 PM

REDIS 데이터 만료 전략에는 두 가지 유형이 있습니다. 정기 삭제 : 만료 된 기간 캡-프리브-컨트 컨트 및 만료 된 시간 캡-프레임 딜레이 매개 변수를 통해 설정할 수있는 만료 된 키를 삭제하기위한주기 스캔. LAZY DELETION : 키를 읽거나 쓰는 경우에만 삭제가 만료 된 키를 확인하십시오. 그것들은 게으른 불쾌한 말입니다. 게으른 유발, 게으른 게으른 expire, Lazyfree Lazy-user-del 매개 변수를 통해 설정할 수 있습니다.

Debian Readdir의 성능을 최적화하는 방법 Debian Readdir의 성능을 최적화하는 방법 Apr 13, 2025 am 08:48 AM

Debian Systems에서 ReadDir 시스템 호출은 디렉토리 내용을 읽는 데 사용됩니다. 성능이 좋지 않은 경우 다음과 같은 최적화 전략을 시도해보십시오. 디렉토리 파일 수를 단순화하십시오. 대규모 디렉토리를 가능한 한 여러 소규모 디렉토리로 나누어 읽기마다 처리 된 항목 수를 줄입니다. 디렉토리 컨텐츠 캐싱 활성화 : 캐시 메커니즘을 구축하고 정기적으로 캐시를 업데이트하거나 디렉토리 컨텐츠가 변경 될 때 캐시를 업데이트하며 readDir로 자주 호출을 줄입니다. 메모리 캐시 (예 : Memcached 또는 Redis) 또는 로컬 캐시 (예 : 파일 또는 데이터베이스)를 고려할 수 있습니다. 효율적인 데이터 구조 채택 : 디렉토리 트래버스를 직접 구현하는 경우 디렉토리 정보를 저장하고 액세스하기 위해보다 효율적인 데이터 구조 (예 : 선형 검색 대신 해시 테이블)를 선택하십시오.

See all articles