Loading...

SpringBoot+Mybatis+redis 入门

avatar

JimXu

2019-09-27

JAVA

SpringBoot+Mybatis+redis 入门

*学无止境啊,坚持就是胜利。*今天就写一篇SpringBoot+Mybatis+redis的查询功能,在没有redis缓存的时候查询数据库,有redis缓存的时候用缓存,当然,先得保证你已经安装好redis,具体的安装方法我就不多说了,网上教程一大堆,开始把

创建Maven工程

导入依赖

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>2.0.4.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!--mysql驱动版本不对就自己换-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.26</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
    </dependencies>

项目结构

配置application.properties

server.port=8082
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/study
spring.datasource.username=root
spring.datasource.password=1234

#mybatis
mybatis.type-aliases-package=top.jimxu.entity
mybatis.mapper-locations=classpath:mapper/*.xml

#redis
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.timeout=5000
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-wait=-1
spring.redis.jedis.pool.min-idle=0

开始写代码

Application.java

package top.jimxu;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

Controller.java

package top.jimxu.controller;

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

@RestController
public class Controller {
    @RequestMapping("hello")
    public String hello(){
        return  "hello SpringBoot!";
    }
}

先运行测试一下

OK,继续吧

User.java

package top.jimxu.entity;

public class User {
    private  Integer id;
    private String username;
    private String password;

    public Integer getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

实体都写了,我竟然忘了数据库,补上

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) NOT NULL,
  `password` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'admin', '123456');

然后再resources里面新建个mapper文件放UserMapper.xml

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="top.jimxu.dao.UserMapper">
    <select id="select" parameterType="int" resultType="top.jimxu.entity.User">
        select * from user where id = #{id}
    </select>
</mapper>

新建dao.UserMapper接口

UserMapper.java

package top.jimxu.dao;

import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import top.jimxu.entity.User;

@Mapper
@Repository
public interface UserMapper {
//    这里的select对应UserMapper.xml的id
    User select(int id);
}

UserService接口

package top.jimxu.service;

public interface UserService {
    String select(int id);
}

UserServiceImpl类

package top.jimxu.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import top.jimxu.dao.UserMapper;
import top.jimxu.entity.User;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ObjectMapper mapper;


    public String select(int id) {
        String json = redisTemplate.opsForValue().get("user");
        if (json==null) {
            User user =  userMapper.select(id);
            try {
                json = mapper.writeValueAsString(user);
            }catch (Exception e){
                return null;
            }
            redisTemplate.opsForValue().set("user",json);
        }
        return  json;
    }
}

然后在Controller加入

@Autowired
    private UserService userService;
@RequestMapping("getuserbyid")
    public String getUserById(int id){
        return userService.select(id);
    }

然后启动redis服务

运行application.java输入localhost:8082/getuserbyid?id=1

可以看到获取到了json数据,而且redis也缓存了数据

到此就结束了,但是查询虽然缓存了,有增加,修改,删除操作的时候记得将redis缓存清理一次哦,不然数据一直用的缓存.....

-->

Other article