十八SpringBoot2核心技术——整合redis

Posted 上善若水

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了十八SpringBoot2核心技术——整合redis相关的知识,希望对你有一定的参考价值。

SpringBoot集成Redis

1.1、目标

完善根据学生id查询学生总数的功能,先从redis缓存中查找,如果找不到,再从数据库中查找,然后放到redis缓存中。

1.2、实现步骤

1.2.1、在pom.xml文件中添加redis依赖

<dependencies>
    <!--SpringBoot框架web项目起步依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--mysql驱动-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <!--mybatis整合springboot框架的起步依赖-->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>${mybatis-spring.version}</version>
    </dependency>
    <!--SpringBoot集成redis的起步依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
</dependencies>

1.2.2、SpringBoot核心配置文件

# springboot核心配置文件
# 指定内嵌 tomcat 端口号
server:
  port: 8080
  servlet:
    context-path: / # 指定上下文根,默认 /

# 设置连接数据库的配置
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springdb?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8
    username: root
    password: root
  redis:
    host: 127.0.0.1
    port: 6379
    password: clgg!321

# 指定mybatis映射文件的路径
mybatis:
  mapper-locations: classpath:mapper/*.xml

1.2.3、启动redis服务,此处采用本地redis环境

1.2.4、controller、service、mapper层类


Student.java

package com.xbmu.pojo;

import java.io.Serializable;

public class Student implements Serializable {
    private Integer id;
    private String name;
    private Integer age;
    /*省略set、get方法*/
}

RedisController.java

package com.xbmu.controller;

import com.xbmu.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class RedisController {

    @Autowired
    private StudentService studentService;

    @RequestMapping("/springboot/allStudentCount")
    public @ResponseBody Object allStudentCount(){
        Long allStudentCount = studentService.queryAllStudentCount();
        return allStudentCount;
    }
}

StudentService.java

package com.xbmu.service;
public interface StudentService {
    Long queryAllStudentCount();
}

在 StudentServiceImpl 中注入 RedisTemplate 并修改根据 id获取学生总数的方法
配置了上面的步骤,Spring Boot 将自动配置 RedisTemplate,在需要操作 redis 的类中注入 redisTemplate 即可。
注意:Spring Boot 帮我们注入 RedisTemplate 类,泛型里面只能写 <String, String>、 <Object, Object>或者什么都不写
StudentServiceImpl.java

package com.xbmu.service.impl;

import com.xbmu.mapper.StudentMapper;
import com.xbmu.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Override
    public Long queryAllStudentCount() {
        // 设置redisTemplate对象key的序列化方式
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // 从redis缓存中获取总人数
        Long allStudentCount = (Long) redisTemplate.opsForValue().get("allStudentCount");
        // 判断是否为空
        if(null == allStudentCount){
            // 去数据库查询,并存放到redis缓存中
            allStudentCount = studentMapper.selectAllStudentCount();
            redisTemplate.opsForValue().set("allStudentCount",allStudentCount,15, TimeUnit.SECONDS);
        }
        return allStudentCount;
    }
}

StudentMapper.java

package com.xbmu.mapper;

public interface StudentMapper {
    Long selectAllStudentCount();
}

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.xbmu.mapper.StudentMapper">
    <select id="selectAllStudentCount" resultType="java.lang.Long">
        SELECT COUNT(1) FROM t_student
    </select>
</mapper>

1.2.5、启动运行,结果如下:

以上是关于十八SpringBoot2核心技术——整合redis的主要内容,如果未能解决你的问题,请参考以下文章

十六SpringBoot2核心技术——整合jsp

十六SpringBoot2核心技术——整合jsp

二十一SpringBoot2核心技术——整合activiti7

十七SpringBoot2核心技术——整合Mybatis

十七SpringBoot2核心技术——整合Mybatis

十九SpringBoot2核心技术——整合Alibaba Dubbo