10分钟

任务 4 使用 Springboot 整合 Redis

任务目标

在 IDE java 编辑器上编写代码,使用 Springboot 框架整合 Redis,实现基本的用户信息查询功能。

任务步骤

1.配置 java 开发环境

配置 java 开发环境可参考腾讯云社区文章《java 环境之 JDK 配置》。

https://cloud.tencent.com/developer/article/1510025

可使用 COS 网址中的安装包安装 JDK 应用程序。

https://course-public-resources-1252758970.cos.ap-chengdu.myqcloud.com/%E5%AE%9E%E6%88%98%E8%AF%BE/%E4%BD%BF%E7%94%A8SMTP%E5%8F%91%E9%80%81%E9%82%AE%E4%BB%B6/jdk-8u131-windows-x86.exe

验证 java 开发环境是否配置成功,同时按下【Windows+R】键 ,输入“cmd”打开 cmd 端,输入命令:

java -version
查看Java版本

点击回车键,查看到 java 版本,即配置 java 开发环境成功。

配置java开发环境成功

2.安装 java 开发编辑工具 IntelliJ IDEA

可通过在 IntelliJ IDEA 官网上等方式下载 IntelliJ IDEA 编辑工具。

IntelliJ IDEA 官网网址:https://www.jetbrains.com/idea/

注意:IntelliJ IDEA官网上有两种版本:商业版和开源版,请下载商业版。

双击打开 IntelliJ IDEA,出现以下页面,即安装完成。

安装完成

3.安装完成后打开,出现下面的页面,此时选择【Create New Project】选项,创建一个新项目。

创建新项目

在左侧导航栏中选择【Spring Initializr】,并设置 SDK,即选择 JDK 路径。

选择项目类别

更改组名为“com.redis”,使项目更容易分辨。

更改组名

选择图中右侧的依赖。

选择集成种类

设置项目名称和项目在本地的地址,然后点击【Finish】。

设置项目名

打开页面,在页面右下角弹出引入依赖包的选项,选择【Enable Auto-Import】。

打开自动导入选项

4.本实验按照以下路径创建文件夹和文件

项目路径结构

5.编写每个部分的代码

1)删掉【application.properties】文件,创建【application.yml】文件,在其中添加以下代码:

spring:
  redis:
    # 此处需要改为自己创建的云数据库Redis的地址
    host: 172.16.0.20
    # 此处需要改为自己创建的云数据库Redis的端口号,默认为6379
    port: 6379
    # 此处需要改为自己创建的云数据库Redis的密码
    password: 311887Zzx

  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    # 此处需要改为自己创建的云数据库MySQL的内网地址:端口号/数据库名
    url: jdbc:mysql://172.16.0.29:3306/Test?useUnicode=true&autoReconnect=true&allowMultiQueries=true&useSSL=false
    # 此处需要改为自己创建的云数据库MySQL的用户名,默认为root
    username: root
    # 此处需要改为自己创建的云数据库MySQL的密码
    password: 311887Zzx

mybatis:
  mapper-locations: classpath:mapper/*.xml

server:
  port: 8381
# 在打印日志时过滤出关于MySQL的日志,用于观察使用redis二级缓存后两次查询数据方式的变化
logging:
  level:
    root: error
    com.redis.dao: debug

其中,要注意以下几点:

  • url: jdbc:mysql: 后应填写自己创建的云数据库 MySQL 的外网地址:端口号/数据库名,如本实验的云数据库 MySQL 的内网地址:端口号/数据库名为 172.16.0.29:3306/Test,此处需要改为自己的配置信息。
  • username: 后应填写自己创建的云数据库 MySQL 的用户名,默认为root。
  • password: 后应填写自己创建的云数据库 MySQL 的密码,如本实验的云数据库 MySQL 的密码是311887Zzx
  • host: 后应填写自己创建的云数据库 Redis 的地址,如本实验的云数据库 Redis 的地址为 172.16.0.20
  • port: 后应填写自己创建的云数据库 Redis 的端口号,默认为 6379。
  • password: 后应填写自己创建的云数据库 Redis 的密码,如本实验的云数据库 Redis 的密码是 311887Zzx

2)【DemoApplication.java】文件代码如下:

package com.redis;

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

@EnableCaching
@EnableTransactionManagement
@MapperScan("com.redis.dao")
@SpringBootApplication
public class DemoApplication {

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

3)【User.java】文件代码如下:

package com.redis.domain;

import java.io.Serializable;

public class User implements Serializable {
    //实现序列化
    private static final long serialVersionUID = 1L;

    private int id;
    private int name;
    private int price;
    private int address;
    private int weight;

    public int getId() {
        return id;
    }

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

    public int getName() {
        return name;
    }

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

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public int getAddress() {
        return address;
    }

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

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }
}

4)【UserMapper.java】文件代码如下:

package com.redis.dao;

import com.redis.domain.User;
import org.springframework.cache.annotation.EnableCaching;

import java.util.List;

@EnableCaching
public interface UserMapper {
    List<User> selectAllUser();
}

5)【UserService.java】文件代码如下:

package com.redis.service;

import com.redis.domain.User;
import java.util.List;

public interface UserService {
    List<User> selectAllUser();
}

6)【UserServiceImp.java】文件代码如下:

package com.redis.service.imp;

import com.redis.dao.UserMapper;
import com.redis.domain.User;
import com.redis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.List;

@Service(value = "userService")
@CacheConfig(cacheNames = "USER")
public class UserServiceImp implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    @Cacheable
    public List<User> selectAllUser() {
        return userMapper.selectAllUser();
    }
}

7)【UserController.java】文件代码如下:

package com.redis.controller;

import com.redis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@EnableAutoConfiguration
@RequestMapping("/query")
public class UserController {

    @Autowired
    private UserService userService;

    @ResponseBody
    @RequestMapping("/findAll")
    public Object findAll() {
        return userService.selectAllUser();
    }
}

8)【UserMapper.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.redis.dao.UserMapper">

    <resultMap id="userMap" type="com.redis.domain.User">
        <id column="ID" property="id"/>
        <result column="NAME" property="name"/>
        <result column="PRICE" property="price"/>
        <result column="ADDRESS" property="address"/>
        <result column="WEIGHT" property="weight"/>
    </resultMap>

    <select id="selectAllUser" resultMap="userMap">
        SELECT * FROM t1
    </select>

</mapper>

此时项目代码部分编写完成。下面是本实验的 demo 下载链接,可直接下载进行参考。

https://course-public-resources-1252758970.cos.ap-chengdu.myqcloud.com/%E5%AE%9E%E6%88%98%E8%AF%BE/Redis%E5%AE%9E%E7%8E%B0%E4%BA%8C%E7%BA%A7%E7%BC%93%E5%AD%98/springboot-redis.zip