SpringBoot-MybatisPlus-Redis 做数据的缓存

2021/7/27 19:05:49

本文主要是介绍SpringBoot-MybatisPlus-Redis 做数据的缓存,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.数据准备

        Mysql数据库

-- ----------------------------
-- Table structure for province
-- ----------------------------
DROP TABLE IF EXISTS `province`;
CREATE TABLE `province`  (
  `pid` int(11) NOT NULL AUTO_INCREMENT,
  `pname` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`pid`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 13 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of province
-- ----------------------------
INSERT INTO `province` VALUES (1, '广东');
INSERT INTO `province` VALUES (2, '湖北');
INSERT INTO `province` VALUES (3, '湖南');
INSERT INTO `province` VALUES (4, '四川');
INSERT INTO `province` VALUES (5, '山东');
INSERT INTO `province` VALUES (6, '山西');
INSERT INTO `province` VALUES (7, '广西');
INSERT INTO `province` VALUES (8, '河北');
INSERT INTO `province` VALUES (9, '云南');
INSERT INTO `province` VALUES (10, '江西');
INSERT INTO `province` VALUES (11, '浙江');
INSERT INTO `province` VALUES (12, '辽宁');

SET FOREIGN_KEY_CHECKS = 1;

2.创建spring-boot项目 导入依赖

<properties>
<!--        jdk版本-->
        <java.version>1.8</java.version>
<!--        外部引入jar包版本-->
        <mysql.version>5.1.49</mysql.version>
        <mybatis.plus.version>3.4.3.1</mybatis.plus.version>
        <druid.version>1.1.23</druid.version>
    </properties>
    <dependencies>
<!--        druid连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>${druid.version}</version>
        </dependency>
<!--        jdbc-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
<!--        aop切面-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
<!--        redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
<!--        web-->
        <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>
<!--        mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
<!--        配置索引-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
<!--        lombok插件-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
<!--        test-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
<!--        mybatisPlus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>${mybatis.plus.version}</version>
        </dependency>
<!--        mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>
<!-- 打包-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

3.spring-boot配置文件

#spring 数据库配置
spring:
  datasource:
    url: jdbc:mysql://数据库地址:端口号/数据库名称?serverTimezone=Asia/Shanghai&characterEncoding=UTF-8&useSSL=false
    username: 账户
    password: 密码
    druid:
      max-active: 10
      min-idle: 5
#Redis
  redis:
    host: redis地址
#mybatis-plus配置sql语句
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

4.javabean

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;


@Data
@AllArgsConstructor //全参构造
@NoArgsConstructor //无参构造
@TableName("province")
public class Province implements Serializable {
  //声明当前属性为主键,并且为自增类型
  @TableId(type = IdType.AUTO)
  private Integer pid;
  private String pname;
}

5. RedisConfi 配置类

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.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 设置Redis序列化规则配置类
 */
//声明当前类时spring-boot配置类
@Configuration
public class RedisConfig {
    /**
     * 配置序列化规则
     * @param redisConnectionFactory 链接工厂
     * @return RedisTemplate
     */
    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        //让当前自定义的RedisTemplate绑定链接转换工厂
        template.setConnectionFactory(redisConnectionFactory);
        //设置当前模板的key的序列化规则
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
        //设置value的序列化规则
        JdkSerializationRedisSerializer jdkSerializationRedisSerializer = new JdkSerializationRedisSerializer();
        //template.setHashValueSerializer(stringRedisSerializer);
        //template.setValueSerializer(stringRedisSerializer);
        template.setValueSerializer(jdkSerializationRedisSerializer);
        template.setHashValueSerializer(jdkSerializationRedisSerializer);
        return template;
    }
}

6.Aop配置类

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * spring-boot中配置aop切面类 @Aspect
 */
@Configuration
@Aspect //声明当前类为切面类
public class MyAspectConfig {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    //@Around("execution(* com.rimi.service.impl.ProvinceServiceImpl.findAllProvince())")
    @Around("execution(* com.baomidou.mybatisplus.extension.service.IService.list())")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //方法执行前(前置通知)
        BoundValueOperations<String, Object> provincesOperations = redisTemplate.boundValueOps("provinces");
        Object provinces = provincesOperations.get();
        if (provinces != null){
            return provinces;
        }
        System.out.println("findAll执行前");
        //要增强的原方法
        Object proceed = joinPoint.proceed();
        //将从数据库查询的数据写入Redis缓存
        //方法执行后(后置通知)
        provincesOperations.set(proceed);
        System.out.println("findAll执行后");
        return proceed;
    }
}

7.controller层

import com.rimi.bean.Province;
import com.rimi.service.ProvinceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("provinces")
public class ProvinceController {

    @Autowired
    private ProvinceService provinceService;

    @GetMapping("")
    public List<Province> getProvinces(){
        //调用mybatis-plus的service-crud方法查询
        return provinceService.list();
        //调用mybatis-mapper-crud方法查询
        //return provinceService.findAllProvince();
    }

    @GetMapping("/{id}")
    public Province getProvinceById(@PathVariable("id") Integer pid){
        //调用mybatis-plus的service-crud方法查询
          return provinceService.getById(pid);
        //调用mybatis-mapper-crud方法查询
        //return provinceService.findProvinceById(pid);
    }

}

8.service层与impl

import com.baomidou.mybatisplus.extension.service.IService;
import com.rimi.bean.Province;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public interface ProvinceService extends IService<Province> {
    /**
     * 查询所有省份
     * @return
     */
    List<Province> findAllProvince();

    /**
     * 根据Id查询省份
     * @param pid
     * @return
     */
    Province findProvinceById(Integer pid);
}
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rimi.bean.Province;
import com.rimi.mapper.ProvinceMapper;
import com.rimi.service.ProvinceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class ProvinceServiceImpl extends ServiceImpl<ProvinceMapper,Province> implements ProvinceService {

    @Autowired
    private ProvinceMapper provinceMapper;

    @Override
    public List<Province> findAllProvince() {
        return provinceMapper.selectList(null);
    }

    @Override
    public Province findProvinceById(Integer pid) {
       return provinceMapper.selectById(pid);
    }
}

9.mapper层

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.rimi.bean.Province;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface ProvinceMapper extends BaseMapper<Province> {

}



这篇关于SpringBoot-MybatisPlus-Redis 做数据的缓存的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程