1. 程式人生 > >springboot和redis的結合使用

springboot和redis的結合使用

啟動jar包,pom.xml檔案新增依賴

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

application.properties中新增redis連線資訊

# Redis資料庫索引(預設為0)
	spring.redis.database=0
	# Redis伺服器地址
	spring.redis.host=127.0.0.1
	# Redis伺服器連線埠
	spring.redis.port=6379
	# Redis伺服器連線密碼(預設為空)
	spring.redis.password=
	# 連線池最大連線數(使用負值表示沒有限制)
	spring.redis.pool.max-active=8
	# 連線池最大阻塞等待時間(使用負值表示沒有限制)
	spring.redis.pool.max-wait=-1
	# 連線池中的最大空閒連線
	spring.redis.pool.max-idle=8
	# 連線池中的最小空閒連線
	spring.redis.pool.min-idle=3
	# 連線超時時間(毫秒)
	spring.redis.timeout=100

application.properties

#spring.datasource.platform=mysql
#spring.datasource.url=jdbc:mysql://localhost/mydb
#spring.datasource.username=root
#spring.datasource.password=hnqy
#spring.datasource.driverClassName=com.mysql.jdbc.Driver

logging.level.com.teng.springboot02.mapper=trace

spring.datasource.platform=oracle
spring.datasource.driverClassName=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521/orcl
spring.datasource.username=jtf
spring.datasource.password=123456

server.port=8080
server.session-timeout=30
server.tomcat.uri-encoding=UTF-8

#####springboot 整合 mybatis

mybatis.mapper-locations= classpath:/com/teng/springboot02/mapper/*Mapper.xml
#mybatis.config-location= classpath:/com/teng/springboot02/config/mybatis-config.xml
#####定義別名
mybatis.type-aliases-package=com.teng.springboot02.domain

###Thymeleaf配置
spring.thymeleaf.prefix=classpath:/view/
spring.thymeleaf.suffix=.html
spring.thymeleaf.cache=false
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML5

###過濾中文亂碼
spring.http.encoding.force=true
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true

# 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.jedis.pool.max-idle=8

入口類Springboot01Application中新增@EnableCaching註解,開啟快取功能

@SpringBootApplication
@EnableCaching
public class Springboot02Application {

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

}

在Service類中要快取的方法上新增@Cacheable

TeacherServiceImpl

@Service
public class TeacherServiceImpl implements TeacherService {
    @Resource
    private TeacherMapper teacherMapper;

    public List<Teacher> selectAllTeacher() {
        return null;
    }

    //對當前方法中儲存的資料進行快取 value="TeacherList" 給key起名
    @Cacheable(value = "TeacherList")
    @Override
    public List<Teacher> findAllTeacher() {
        return teacherMapper.findAllTeacher();
    }

    //當執行該方法時,強制清空指定的快取
    @CacheEvict(value = "TeacherList",allEntries = true)
    @Override
    public void deleteTeacher(int id) {
        System.out.println("--------------------");
    }

    @Override
    @Cacheable(value = "#tid",key="T(String).valueOf(#tid)")
    public Teacher findTeacherById(int tid) {
        Teacher teacher = teacherMapper.findTeacherById(tid);
       return teacher;
    }
//更新一個物件,在redis中清空一個物件
    @Override
    @CachePut(value = "#tid",key ="T(String).valueOf(#tid)")
    public Teacher updateTeacher(@Param("tid")int tid,@Param("Teacher")Teacher teacher) {
        teacherMapper.updateTeacher(teacher);
        Teacher teacher1 = teacherMapper.findTeacherById(tid);
        return teacher1;
    }

    public void setTeacherMapper(TeacherMapper teacherMapper) {
        this.teacherMapper = teacherMapper;
    }
}

TeacherService

package com.teng.springboot02.service;


import com.teng.springboot02.domain.Teacher;

import java.util.List;

public interface TeacherService {
    public List<Teacher> selectAllTeacher();
    public List<Teacher> findAllTeacher();
    public void deleteTeacher(int id);
    public Teacher findTeacherById(int id);
    public Teacher updateTeacher(int tid,Teacher teacher);

}

controller
TeacherController

package com.teng.springboot02.controller;

import com.alibaba.fastjson.JSON;
import com.teng.springboot02.domain.Teacher;
import com.teng.springboot02.service.TeacherService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;

@RestController
public class TeacherController {
    @Resource
    private TeacherService teacherService;
    @RequestMapping("/showTeacher")
    public String showTeacher(){
        List list1 = teacherService.findAllTeacher();
        return JSON.toJSONString(list1);
    }
    @RequestMapping("/delete")
    public String delete(int tid) {
        teacherService.deleteTeacher(tid);
        return "true";
    }
    @RequestMapping("/find")
    public String find(int tid) {
        Teacher teacher = teacherService.findTeacherById(tid);
        return JSON.toJSONString(teacher);
    }
    @RequestMapping("/update")
    public String update(Teacher teacher) {
       teacherService.updateTeacher(teacher.getId(),teacher);
        return "true";
    }
    public void setTeacherService(TeacherService teacherService) {
        this.teacherService = teacherService;
    }
}

domain
Stu

package com.teng.springboot02.domain;

public class Stu implements java.io.Serializable{

    private Integer id;
    private String name;
    private Integer teacherId;
    private String className;
    private Teacher teacher;

    public Teacher getTeacher() {
        return teacher;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public Integer getTeacherId() {
        return teacherId;
    }

    public void setTeacherId(Integer teacherId) {
        this.teacherId = teacherId;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }
}

Teacher

package com.teng.springboot02.domain;

import sun.plugin2.message.Serializer;

import java.util.List;

public class Teacher implements java.io.Serializable{

    private Integer id;
    private String name;
    private String className;
    private List<Stu> stus;

    public List<Stu> getStus() {
        return stus;
    }

    public void setStus(List<Stu> stus) {
        this.stus = stus;
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }
}

mapper
TeacherMapper

package com.teng.springboot02.mapper;

import com.teng.springboot02.domain.Teacher;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;

import java.util.List;

@Mapper
@Component
public interface TeacherMapper {
    public List<Teacher> selectAllTeacher();
    public List<Teacher> findAllTeacher();
    public Teacher findTeacherById(int id);
    public int updateTeacher(Teacher teacher);

}

TeacherMapper.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">
<!--namespace 名稱空間 唯一的-->
<mapper namespace="com.teng.springboot02.mapper.TeacherMapper">
    <!--一對多的第一種寫法,一般考慮到效能,不會這樣實現-->
    <resultMap id="TeacherMap" type="Teacher" autoMapping="true">
    <collection property="stus" ofType="Stu" column="id" autoMapping="true">
    </collection>
    </resultMap>
    <!--查詢所有的老師及各自的所有學生,第一種形式 一一對應-->
    <select id="selectAllTeacher" parameterType="Teacher" resultMap="TeacherMap">
        select t.id,t.name,t.class_name,
        s.id as sid,s.name as sname,s.class_name as className
        from
        teacher t join stu s
        on t.id = s.teacher_id
    </select>
    <resultMap type="Teacher" id="teacherMaps" autoMapping="true">
        <collection property="stus" ofType="Stu" select="getStudents" column="id">
        </collection>
    </resultMap>
    <!-- 查詢所有的老師級各自的所有學生,一對多關聯-->
    <select id="findAllTeacher" parameterType="Teacher" resultMap="teacherMaps">
		SELECT
			t.id,
			t.name,
			t.class_name
		FROM
			teacher t
	</select>
    <select id="getStudents" parameterType="int" resultType="Stu">
		select
			s.id,
			s.name,
			s.class_name as className
		from stu s
		where teacher_id = #{id}
	</select>

    <select id="findTeacherById" resultType="Teacher">
        select * from teacher where id = #{tid}
    </select>

    <update id="updateTeacher" parameterType="Teacher">
        update teacher set name=#{name} where id =#{id}
    </update>
</mapper>

測試

在這裡插入圖片描述
在這裡插入圖片描述清空控制檯
再次訪問,返回資料
在這裡插入圖片描述
控制檯沒有訪問資料庫,說明查詢時走的快取
在這裡插入圖片描述
強制清空指定的快取
在這裡插入圖片描述
控制檯輸出,說明執行方法成功
在這裡插入圖片描述
再次訪問showTeacher,控制檯輸出,說明沒訪問快取
在這裡插入圖片描述