SpringBoot使用缓存注解

本文详细介绍了如何在SpringBoot项目中整合MyBatis与Redis,实现数据缓存功能。通过创建实体类、配置数据源、启用缓存注解、编写Mapper与Service层代码,展示了完整的开发流程。同时,解决了缓存对象序列化问题,确保了应用的正常运行。

数据库创建如下

create table test(
    id int primary key,
    username varchar(20),
    password varchar(20)
)

1.在entity包下创建一个User类

package com.liqiang.demo.entity;

import java.io.Serializable;
/*
 * @Author: liqiang
 * @Date: 2019-7-4 15:54
 * */
public class User implements Serializable{
	private int id;
    private String username;
    private String password;
	public int getId() {
		return id;
	}
	public void setId(int 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;
	}
     
}

2.application.properties

#thymeleaf
spring.thymeleaf.cache=false
spring.thymeleaf.mode=LEGACYHTML5

spring.datasource.url=jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
spring.datasource.password=数据库密码

spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.username=root


spring.redis.host = localhost
spring.redis.port = 6379
//redis密码默认为空
spring.redis.password=
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

logging.level.com.liqiang.demo.mapper = debug

mybatis.configuration.map-underscore-to-camel-case=true

3.开启基于注解的@EnableCaching

 package com.liqiang.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@ServletComponentScan
@EnableCaching
public class SpringbootDemo01Application {

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

4.mapper层代码

package com.liqiang.demo.mapper;
import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;

import com.liqiang.demo.entity.User;

/*
 * @Author: liqiang
 * @Date: 2019-7-4 15:54
 * */
@Mapper
@Repository
public interface UserMapper {

     @Select("select * from test where id=#{id}")
     User getUser(@Param("id") int id);
	 
     @Select("select * from test")
     List<User> getAllUser();
     
}

5.service层(这里为了简化,并没有继承接口来方便以后拓展功能)

package com.liqiang.demo.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.liqiang.demo.entity.User;
import com.liqiang.demo.mapper.UserMapper;
/*
 * @Author: liqiang
 * @Date: 2019-7-4 15:54
 * */
@Service
public class UserService {
     @Autowired
     private UserMapper userMapper;
     
     @Cacheable(cacheNames= {"emp"},key="#id")
     public User getUser(Integer id) {
    	 System.out.println("查询"+id+"号员工");
    	 User user= userMapper.getUser(id);
    	 return user;
     }
     
     
     public List<User> getAllUser(){
    	 List<User> lists = userMapper.getAllUser();
    	 return lists;
     }
}

6.controller层

package com.liqiang.demo.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.liqiang.demo.entity.User;
import com.liqiang.demo.service.UserService;

/*
 * @Author: liqiang
 * @Date: 2019-7-4 15:54
 * */
@RestController
public class TestController {
	@Autowired
	private RedisTemplate<String,Object> redisTemplate;
	@Autowired
	private UserService userService;
	
	@RequestMapping("/user/get/{id}")
	public User getUser(@PathVariable("id")Integer id) {
		return userService.getUser(id);
	}
	
	
	@RequestMapping("/user/getAll")
	public List<User> getAllUser(){
		return userService.getAllUser();
	}
	
}

如果出现以下错误

DefaultSerializer requires a Serializable payload but received an object of type [model.Admin]

一.问题描述:

  DefaultSerializer requires a Serializable payload but received an object of type [model.Admin]

二.问题分析:

  要缓存的 Java 对象必须实现 Serializable 接口,因为 Spring 会将对象先序列化再存入 Redis

三.解决方法:

 将缓存实体类继承 Serializable

 

public class Admin implements Serializable

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值