美文网首页
SpringBoot+MyBatis+Redis

SpringBoot+MyBatis+Redis

作者: 煗NUAN | 来源:发表于2020-04-25 20:45 被阅读0次

    SpringBoot+MyBatis+Redis

    1.新建SpringBoot项目

    01.jpg
    02.jpg

    2.pom文件中添加依赖

    <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.1.2</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.1.15</version>
            </dependency>
            <!--添加servlet依赖模块-->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <scope>provided</scope>
            </dependency>
            <!-- 添加jstl标签库依赖模块 -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
            </dependency>
            <!--添加tomcat依赖模块.-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
                <scope>provided</scope>
            </dependency>
            <!--rest-->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.8.10</version>
            </dependency>
            <!--redis依赖:spring-boot-starter-data-redis-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
            </dependency>
            <!--redis依赖:spring-boot-starter-json-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-json</artifactId>
            </dependency>
    
    • 完整的pom文件
    <?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.2.6.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.ym</groupId>
        <artifactId>spring_boot_redis</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>war</packaging>
        <name>spring_boot_redis</name>
        <description>Demo project for Spring Boot</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-devtools</artifactId>
                <scope>runtime</scope>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
                <exclusions>
                    <exclusion>
                        <groupId>org.junit.vintage</groupId>
                        <artifactId>junit-vintage-engine</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
    
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.1.2</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.1.15</version>
            </dependency>
            <!--添加servlet依赖模块-->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <scope>provided</scope>
            </dependency>
            <!-- 添加jstl标签库依赖模块 -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
            </dependency>
            <!--添加tomcat依赖模块.-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
                <scope>provided</scope>
            </dependency>
            <!--rest-->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.8.10</version>
            </dependency>
            <!--redis依赖:spring-boot-starter-data-redis-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
            </dependency>
            <!--redis依赖:spring-boot-starter-json-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-json</artifactId>
            </dependency>
    
    
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    
    

    3.在resource包下添加application.yml文件

    server:
      port: 8080
      # 指定端口
    spring:
      # 配置数据源
      datasource:
        type: com.alibaba.druid.pool.DruidDataSource
        url: jdbc:mysql://localhost:3307/datatest?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8
        driver-class-name: com.mysql.cj.jdbc.Driver
        username: root
        password: root
      #redis
      redis:
        host: 127.0.0.1
        database: 0
        port: 6379
    # 配置mybatis
    mybatis:
      type-aliases-package: com.ym.pojo
      mapper-locations: classpath*:mapper/*Mapper.xml
    

    4.RedisConfig.java

    package com.ym.config;
    
    import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
    import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.connection.RedisConnectionFactory;
    import org.springframework.data.redis.core.RedisOperations;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.core.StringRedisTemplate;
    import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
    import org.springframework.data.redis.serializer.StringRedisSerializer;
    
    @Configuration
    @ConditionalOnClass( RedisOperations.class )
    @EnableConfigurationProperties( RedisProperties.class)
    public class RedisConfig {
    
        @Bean
        @ConditionalOnMissingBean(name = "redisTemplate")
        public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
    
            RedisTemplate<Object,Object> template=new RedisTemplate<>();
    
            //使用fastjson实现对于对象的序列化
            Jackson2JsonRedisSerializer serializer=new Jackson2JsonRedisSerializer(Object.class);
    
            //设置"值"的序列化方式
            template.setValueSerializer(serializer);
    
            //设置"hash"类型的序列化方式
            template.setHashValueSerializer(serializer);
    
            //设置"key"的序列化方式
            template.setKeySerializer(new StringRedisSerializer());
    
            //设置"hash的key"的序列化方式
            template.setHashKeySerializer(new StringRedisSerializer());
    
            //设置redis模式的工厂对象
            template.setConnectionFactory(redisConnectionFactory);
    
            return template;
        }
    
        @Bean
        @ConditionalOnMissingBean(StringRedisTemplate.class)
        public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory){
            StringRedisTemplate template=new StringRedisTemplate();
    
            template.setConnectionFactory(redisConnectionFactory);
    
            return template;
        }
    }
    
    

    5.pojo层User

    package com.ym.pojo;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class User {
        private int uid;
        private String name;
        private String sex;
        private int age;
        private String address;
    }
    

    6.dao层接口

    • 接口上需要@Mapper注解
    package com.ym.dao;
    
    import com.ym.pojo.User;
    import org.apache.ibatis.annotations.Mapper;
    
    import java.util.List;
    
    
    @Mapper //接口上有注解
    public interface IUserDao {
        List<User> getAllUsers();
    }
    

    7.resource包下新建mapper包,并新建与接口对应的xml文件

    • UsersMapper.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属性 -->
    <mapper namespace="com.ym.dao.IUserDao">
    
        <sql id="all">
            select * from users
        </sql>
    
        <select id="getAllUsers" resultType="user">
            <include refid="all" />
        </select>
    </mapper>
    

    8.service层接口IUserService.java

    package com.ym.service;
    
    import com.ym.pojo.User;
    
    import java.util.List;
    
    public interface IUserService {
        List<User> getAllUsers();
    }
    

    9.service层接口的实现类UserService.java

    package com.ym.service.impl;
    
    import com.ym.dao.IUserDao;
    import com.ym.pojo.User;
    import com.ym.service.IUserService;
    import org.springframework.data.redis.core.ListOperations;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.stereotype.Service;
    
    import javax.annotation.Resource;
    import java.util.List;
    
    @Service
    public class UserService implements IUserService {
    
        @Resource
        private IUserDao userDao;
    
        @Resource
        private RedisTemplate redisTemplate;
    
        @Override
        public List<User> getAllUsers() {
    
            String key="user";
            ListOperations<String,User> operations=redisTemplate.opsForList();
    
            //缓存存在
            if (redisTemplate.hasKey(key)){
                System.out.println("缓存中的内容");
                return operations.range(key, 0, -1);
            }else {
                //获取所有信息
                List<User> allUsers = userDao.getAllUsers();
                operations.leftPushAll(key,allUsers);
                System.out.println("数据库中的内容");
                return allUsers;
            }
        }
    }
    

    10.controller层实现类

    package com.ym.controller;
    
    import com.ym.pojo.User;
    import com.ym.service.IUserService;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import javax.annotation.Resource;
    import java.util.List;
    
    @Controller
    public class UserController {
    
        @Resource
        private IUserService userService;
    
        @GetMapping("/getAllUser")
        @ResponseBody
        public List<User> getAllUser(){
            List<User> users = userService.getAllUsers();
            return users;
        }
    
    }
    

    11.测试验证

    • 请求成功截图


      请求成功截图.png
    • 第一次请求(redis中不存在,查询数据中的值,返回到页面,并保存到redis中)


      第一次请求数据库中的值.png
    • 第二次请求(redis中已存在,获取redis中的值)


      第二次请求redis中的值.png

    相关文章

      网友评论

          本文标题:SpringBoot+MyBatis+Redis

          本文链接:https://www.haomeiwen.com/subject/lvhlwhtx.html