IDEA搭建SpringBoot+Mybatis+Redis

孤者浪人 提交于 2019-12-01 00:15:03

1,新建一个项目

2,下一步

3,下一步,Web选项勾选web,SQL选项勾选MySQL,MyBatis

4,点击完成创建完项目:

5,配置pom.xml文件

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.stu</groupId>
    <artifactId>springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>springboot</name>
    <description>Demo project for Spring Boot</description>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <spring-boot-starter-redis-version>1.3.2.RELEASE</spring-boot-starter-redis-version>
    </properties>
    <dependencies>
        <!-- Spring Boot Reids 依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
            <version>${spring-boot-starter-redis-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.stu</groupId>
            <artifactId>springboot</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.25</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.8</version>
        </dependency>
        <dependency>
            <groupId>org.apache.ibatis</groupId>
            <artifactId>ibatis-core</artifactId>
            <version>3.0</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>6,配置application.properties文件
#设置spring-boot 编码格式
spring.banner.charset=UTF-8
server.tomcat.uri-encoding=UTF-8
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
spring.messages.encoding=UTF-8
## Redis 配置
## Redis数据库索引(默认为0)
spring.redis.database=0
## Redis服务器地址
spring.redis.host=127.0.0.1
## Redis服务器连接端口
spring.redis.port=6379
## Redis服务器连接密码(默认为空)
spring.redis.password=123456
## 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
## 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
## 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
## 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
## 连接超时时间(毫秒)
spring.redis.timeout=0

7,在resources目录下新建mappers文件

代码:

<?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.stu.springboot.mapper.MastMapper">
    <select id="getEmp"  resultType="Emp">
        select * from emp order by empno
    </select>
    <select id="getEmpByEmpno"  parameterType="string" resultType="Emp">
        select * from emp where empno=#{empno}
    </select>
</mapper>

8,在resources文件夹下新建spring-mybatis.xml文件

代码:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <!--这里是全局配置,具体的可以去查mybatis配置-->
    <settings>
        <setting name="cacheEnabled" value="false" />
        <setting name="useGeneratedKeys" value="true" />
        <setting name="defaultExecutorType" value="REUSE" />
    </settings>
    <typeAliases>
        <typeAlias alias="Emp" type="com.stu.springboot.entity.Emp"/>
    </typeAliases>
    <!--环境配置-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="jdbc"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mysql"/>
                <property name="username" value="root"/>
                <property name="password" value="#EDC4rfv"/>
            </dataSource>
        </environment>
    </environments>
    <!--这个就是指定映射的xml,mapper xml中的SQL查询 都要对应java接口类里面的方法-->
    <mappers>
        <mapper resource="mappers/mapper-mybatis.xml"/>
    </mappers>
</configuration>

9,在java文件下新建 com.stu.springboot.singleton.SingletonMybatis文件

代码:

public class SingletonMybatis {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        String resource = "spring-mybatis.xml";
        Reader reader = null;
        try {
            reader = Resources.getResourceAsReader(resource);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        //这里相当于生成一个数据库管理者,它可以返回一个连接给使用者。
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
    }
    public static SqlSessionFactory getSqlSessionFactory(){
        return sqlSessionFactory;
    }
}

10,在java文件下新建 com.stu.springboot.mapper.MastMapper文件

代码:

public interface MastMapper { public List<Emp> getEmp(); public Emp getEmpByEmpno(String empno); }

11,在service层运用redis缓存:

代码:

@Service("empService")
public class EmpServiceImpl implements EmpService{
    private static final Logger LOGGER = LoggerFactory.getLogger(EmpServiceImpl.class);
    @Autowired
    private EmpDao empDao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public List<Emp> getEmp() {
        // 从缓存中获取员工信息
        String key = "emp_list";
        List<Emp> empList;
        ValueOperations<String, List<Emp>> operations = redisTemplate.opsForValue();
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            empList = operations.get(key);
            System.out.println("从缓存中获取了员工,员工个数 >> " + empList.size());
            return empList;
        }
        // 从 DB 中获取城市信息
        empList = empDao.getEmp();
        // 插入缓存
        operations.set(key, empList);
        System.out.println("员工插入缓存,员工个数 >> " + empList.size());
        return empList;
    }
    @Override
    public Emp getEmpByEmpno(String empno) {
        // 从缓存中获取员工信息
        String key = "emp_" + empno;
        ValueOperations<String, Emp> operations = redisTemplate.opsForValue();
        // 缓存存在
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            Emp emp = operations.get(key);
            System.out.println("从缓存中获取了员工 >> " + emp.toString());
            return emp;
        }
        // 从 DB 中获取城市信息
        Emp emp = empDao.getEmpByEmpno(empno);
        // 插入缓存
        operations.set(key, emp);
        System.out.println("员工插入缓存 >> " + emp.toString());
        return emp;
    }
}

12,实现controller并设计restful api:

@RestController
@SpringBootApplication
public class SpringbootApplication {
    @Autowired
    private EmpService empService;
    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
    }
    @RequestMapping(value = "/",produces = "text/plain;charset=UTF-8")
    String index(){
        System.out.println("enter into index method!");
        return "Hello Spring Boot!";
    }
    @RequestMapping(value = "/empList")
    public List<Emp> getEmp(){
        System.out.println("enter into getEmp method");
        List<Emp> list = empService.getEmp();
        return list;
    }
    @RequestMapping(value = "/emp")
    public Emp getEmpByEmpno(@RequestParam String empno){
        System.out.println("enter into getEmpByEmpno method param is empno = "+empno);
        Emp emp = empService.getEmpByEmpno(empno);
        return emp;
    }
}

13,整个测试项目的结构图:

14,最后需要在本地安装redis,并开启服务。

测试结果:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!