spring-boot 缓存

1 sql

CREATE DATABASE demo;
USE demo;
DROP TABLE IF EXISTS t_article;
CREATE TABLE t_article (
  id int(20) NOT NULL AUTO_INCREMENT COMMENT '文章id',
  title varchar(200) DEFAULT NULL COMMENT '文章标题',
  content longtext COMMENT '文章内容',
  PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO t_article VALUES ('1', 'Spring Boot基础入门','从入门到精通讲解...');	
INSERT INTO t_article VALUES ('2', 'Spring Cloud基础入门', '从入门到精通讲解...');
DROP TABLE IF EXISTS t_comment;
CREATE TABLE t_comment (
  id int(20) NOT NULL AUTO_INCREMENT COMMENT '评论id',
  content longtext COMMENT '评论内容',
  author varchar(200) DEFAULT NULL COMMENT '评论作者',
  a_id int(20) DEFAULT NULL COMMENT '关联的文章id',
  PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

INSERT INTO t_comment VALUES ('1', 'aa', 'a', '1');
INSERT INTO t_comment VALUES ('2', 'bb', 'b', '1');
INSERT INTO t_comment VALUES ('3', 'cc', 'ercic', '1');
INSERT INTO t_comment VALUES ('4', 'dd', 'd','1');
INSERT INTO t_comment VALUES ('5', 'ee', 'e', '2');

2 实体类

@Entity
@Table(name = "t_comment")
public class Comment implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String content;
    private String author;
    @Column(name = "a_id")
    private Integer aId;

    @Override
    public String toString() {
        return "Comment{" +
                "id=" + id +
                ", content='" + content + '\'' +
                ", author='" + author + '\'' +
                ", aId=" + aId +
                '}';
    }
    settter getter ...

3 repository

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

public interface CommentRepository extends JpaRepository<Comment,Integer> {

}

4 service

@Service
public class CommentService {

    @Autowired
    private CommentRepository commentRepository;



    //@Cacheable:  将该方法查询结果comment存放在springboot默认缓存中
     //cacheNames: 起一个缓存命名空间  对应缓存唯一标识

    // value: 缓存结果  key:默认在只有一个参数的情况下,key值默认就是方法参数值 如果没有参数或者多个参数的情况:simpleKeyGenerate
    // 查询方法
    @Cacheable(cacheNames = "comment",unless = "#result==null")
    public Comment findCommentById(Integer id){
        Optional<Comment> byId = commentRepository.findById(id);
        if(byId.isPresent()){
            Comment comment = byId.get();
            return  comment;
        }
        return  null;
    }

5 controller

@RestController
public class CommentController {

    @Autowired
    private CommentService commentService;


    @RequestMapping("/findCommentById")
    public Comment findCommentById(Integer id){
        Comment comment = commentService.findCommentById(id);
        return  comment;

    }
    }

6 application.properties

# MySQL数据库连接配置
spring.datasource.url=jdbc:mysql://192.168.101.111:3306/springbootdata?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
#显示使用JPA进行数据库查询的SQL语句
spring.jpa.show-sql=true

#开启驼峰命名匹配映射
mybatis.configuration.map-underscore-to-camel-case=true
#解决乱码
spring.http.encoding.force-response=true

7 启动类

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

@EnableCaching // 开启spring boot基于注解的缓存管理支持
@SpringBootApplication
public class SpringbootDemoApplication {

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

}

8 测试

http://127.0.0.1:8080/findCommentById?id=1
查看 日志 多次访问 只打印一次

9 拓展

缓存注解
1 @EnableCaching注解 用于开启基于注解的支持
2 @Cacheable注解 作用类或者方法上 用于对方法结果进行缓存
3 @CachePut注解 更新 目标方法执行后生效
4 @CacheEvict注解 删除缓存数据 执行顺序是,先进行方法调用,然后将缓存进行清理

9.1 @cacheable属性值
几个属性
cacheNames/value:指定缓存空间的名字;必须配置的属性,这两个属性二选其一。
key:缓存数据使用的key,可以用它来指定。默认是使用方法参数的值 1-方法的返回值,可以使用SPEL表达式进行指定key。
keyGenerator:key的生成器,key/keyGenerator,二选一使用。
cacheManager:指定缓存管理器
cacheResolver 指定获取解析器,与cacheManager属性二选一使用
condition:指定符合条件的情况下才缓存
unless : 指定符合条件的情况下不进行数据缓存
sync: 知道是否使用异步缓存,默认false
9.2 SimpleKeyGenerator生成key的默认策略

参数个数key
如果没有参数key=new SimpleKey()
如果有一个参数key=参数的值
如果有多个参数key=new SimpleKey(params)
centered 文本居中right-aligned 文本居右

9.3 数据结构
数据结构: SimpleCacheConfiguration ConcurrentMapCacheManager ConcurrentMap<String ,Cache>
key: SimpleKeyGenerator
9.4 spel表达式
https://blog.youkuaiyun.com/yangshangwei/article/details/78157834

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值