SpringBoot常用功能

Spring Cache使用方法与Spring对事务管理的配置相似。Spring Cache的核心就是对某 个方法进行缓存,其实质就是缓存该方法的返回结果,并把方法参数和结果用键值对的 方式存放到缓存中,当再次调用该方法使用相应的参数时,就会直接从缓存里面取出指 定的结果进行返回

相比于redis,springcache没有设置缓存过期时间的功能

 

一、SpringCache使用

使用步骤:

1、在springboot启动类上加注解:@EnableCaching

2、使用@CacheConfig注解,使被注解类被指定存在哪个缓存空间

@CacheConfig(cacheNames = "archives:waterAccountPeriod:service")

3、使用@Cacheable注解,使被注解的查询方法加入缓存:

@Cacheable(value = "gathering",key = "#id", unless = "#result == null")
    public Gathering findById(String id) {
        return gatheringDao.findById(id).get();
    }

其中value是大key,key是小key,相当于redis的hash类型。#是关键字,表示从方法形参(id)中取值

unless后的条件代表如果此方法返回null则不进行缓存

4、使用@CacheEvict注解,令缓存失效:

@CacheEvict(value = "gathering",key = "#id")
    public void deleteById(String id) {
        gatheringDao.deleteById(id);
    }
@CacheEvict(value = "gathering",key = "#gathering.id")
    public void update(Gathering gathering) {
        gatheringDao.save(gathering);
    }

 

二、单机版定时任务

1.在要使用的类上加注解

@EnableScheduling

2.在要执行方法上加注解

@Scheduled(cron = "0 0 8 * * ?")

 

三、编程式事务

方式一:

1.注入事务模板对象

    @Resource
    private TransactionTemplate transactionTemplate;

2.将对应代码(saveMenuRelation方法)用事务包裹

        transactionTemplate.execute(status -> {
            try {
                saveMenuRelation(servicePackMenuDTO);
            } catch (Exception e) {
                log.error("bindMenu, servicePackMenuDTO:{}", servicePackMenuDTO, e);
                status.setRollbackOnly();
            }
            return null;
        });

方式二:

1.注入模板事务管理器和事务定义

    @Resource
    PlatformTransactionManager platformTransactionManager;

    @Resource
    TransactionDefinition transactionDefinition;

2.将对应代码用事务包裹

        TransactionStatus baseInfoTransaction = platformTransactionManager.getTransaction(transactionDefinition);
        try {
            bindCertificationBankInfo(certificationInDto, certificationPingPlusInfo.getBankInfoId());
        } catch (Exception e) {
            platformTransactionManager.rollback(baseInfoTransaction);
            log.error("[{}],初始化认证基础信息异常,请重试!。msg:{}", TAG, e.getMessage(), e);
            throw new RuntimeException("初始化认证基础信息异常,请重试!");
        }
        platformTransactionManager.commit(baseInfoTransaction);

 

posted on 2019-03-13 20:07  bofeng  阅读(388)  评论(0编辑  收藏  举报