springboot +mybatis+ehcache缓存注解

1.在pom.xml中引入cache依赖,添加如下内容:


    org.springframework.boot
    spring-boot-starter-cache

2.在Spring Boot主类中增加@EnableCaching注解开启缓存功能,如下:

@SpringBootApplication
@ComponentScan(basePackages="com.ehcache")//扫描组件
@EnableCaching
public class EhcacheTestApplication {

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

3.application.properyies

server.port=8850

#cache 多个用逗号分开
spring.cache.cache-names=userCache
spring.cache.jcache.config=classpath:ehcache.xml


# datasource
spring.datasource.name=ehcahcetest
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3312/ehcahcetest
spring.datasource.username=root
spring.datasource.password=123456

# mybatis
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
mybatis.config-location=classpath:mybatis/mybatis-config.xml
#mybatis.type-aliases-package=

4.ehcache.xml



    

    
    
    
    
    
    
    

    

    
        
        
        
        
                    
                    
         
        

    

5.加入缓存注解到实现类

@Service
public class UserService {
    
    @Autowired
    private UserDao userDao;

    @CacheEvict(key="'user_'+#uid", value="userCache")
    public void del(String uid) {
        // TODO Auto-generated method stub
        userDao.del(uid);
    }

    @CachePut(key="'user_'+#user.uid", value="userCache")
    public void update(User user) {
        userDao.update(user);
    }
    
    @Cacheable(key="'user_'+#uid",value="userCache")
    public User getUserById(String uid){
        System.err.println("缓存里没有"+uid+",所以这边没有走缓存,从数据库拿数据");
        return userDao.findById(uid);
        
    }

    @CacheEvict(key="'user'",value="userCache")
    public String save(User user) {
        // TODO Auto-generated method stub
        return userDao.save(user);
    }

    
}

 

你可能感兴趣的:(web项目)