前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >springboot和redis的结合使用

springboot和redis的结合使用

作者头像
微醺
发布2019-01-17 12:55:12
7900
发布2019-01-17 12:55:12
举报

启动jar包,pom.xml文件添加依赖

代码语言:javascript
复制
 <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连接信息

代码语言:javascript
复制
# 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

代码语言:javascript
复制
#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注解,开启缓存功能

代码语言:javascript
复制
@SpringBootApplication
@EnableCaching
public class Springboot02Application {

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

}

在Service类中要缓存的方法上添加@Cacheable

TeacherServiceImpl

代码语言:javascript
复制
@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

代码语言:javascript
复制
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

代码语言:javascript
复制
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

代码语言:javascript
复制
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

代码语言:javascript
复制
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

代码语言:javascript
复制
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

代码语言:javascript
复制
<?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,控制台输出,说明没访问缓存

在这里插入图片描述
在这里插入图片描述
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年12月21日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 启动jar包,pom.xml文件添加依赖
  • application.properties中添加redis连接信息
  • 入口类Springboot01Application中添加@EnableCaching注解,开启缓存功能
  • 在Service类中要缓存的方法上添加@Cacheable
  • 测试
相关产品与服务
云数据库 Redis
腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档