分布式缓存 Ehcache整合

Ehcahce缓存
@Cacheable
查询操作,将查询内容存到缓存里,下次获取时从缓存中获取数据。如果缓存中没有数据,则从数据库中读取,并设置到缓存中
@CachePut
添加/修改操作,当数据库中的数据执行添加修改操作时,缓存中的数据也会进行更新。添加时,则刷新缓存对象;修改时,则更新缓存
注:方法需要返回User对象
@CacheEvict
删除操作,数据库数据删除,对应缓存中的数据也删除

pom.xml 依赖添加

<!--ehcache依赖-->
   <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-cache</artifactId>
   </dependency>
   <dependency>
     <groupId>net.sf.ehcache</groupId>
     <artifactId>ehcache</artifactId>
   </dependency>

ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">
    <defaultCache
            eternal="false"
            maxElementsInMemory="1000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="0"
            timeToLiveSeconds="600"
            memoryStoreEvictionPolicy="LRU" />

    <!-- 这里的 users 缓存空间是为了下面的 demo 做准备 -->
    <cache
            name="users"
            eternal="false"
            maxElementsInMemory="100"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="0"
            timeToLiveSeconds="300"
            memoryStoreEvictionPolicy="LRU" />
</ehcache>

application.yml

#    设置ehcache缓存的配置
  cache:
    ehcache:
      config: classpath:ehcache.xml

Starter

@EnableCaching//启用缓存

UserController

用户详情查询缓存

   @GetMapping("user/id/{userId}")
    @Cacheable(value = "users",key = "#userId")
    public User queryUserById(@PathVariable Integer userId){
        return userService.queryUserById(userId);
    }

用户列表查询缓存

//    分页查询
    @RequestMapping("list")
    @Cacheable(value = "users",key = "#userQuery.pageNum+'-'+#userQuery.pageSize+'-'+#userQuery.userName")
    public PageInfo<User>   queryUserByPage(UserQuery userQuery){
        return userService.queryUserByParams(userQuery);
    }

用户更新&删除缓存

//更新用户
   @PutMapping("user03")
    @CachePut(value = "users",key = "#user.id")
    public User updateUser03(@RequestBody @Valid User user){

        //调用service层添加方法,返回map对象
        userService.updateUser(user);
        return  user;
    }




//    删除用户
    @DeleteMapping("user/{userId}")
    @CacheEvict(value = "users",key = "#userId")
    public Map<String,Object> deleteUser(@PathVariable Integer userId){


        Map<String,Object> map = new HashMap<>();
        //调用service层添加方法,返回map对象
        userService.deleteUserById(userId);
        return  map;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值