springBoot配置ehcache 实现缓存策略

第一步:在springboot启动的main函数 加上对缓存的注解 @EnableCaching

第二步:在resource 文件夹下  增加 config文件夹,在文件夹中 增加ehcache.xml文件,用于配置ehcache

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">

    <cache name="userLogCache"
           eternal= "false"
           maxEntriesLocalHeap="0"
           timeToIdleSeconds="200">
    </cache>

    <!-- eternal:true表示对象永不过期,此时会忽略timeToIdleSeconds和timeToLiveSeconds属性,默认为false -->
    <!-- maxEntriesLocalHeap:堆内存中最大缓存对象数,0没有限制 -->
    <!-- timeToIdleSeconds: 设定允许对象处于空闲状态的最长时间,以秒为单位。当对象自从最近一次被访问后,如果处于空闲状态的时间超过了timeToIdleSeconds属性值,这个对象就会过期,EHCache将把它从缓存中清空。只有当eternal属性为false,该属性才有效。如果该属性值为0,则表示对象可以无限期地处于空闲状态 -->
</ehcache>

配置文件的关键字段 是 name="userLogCache"  下文中的UserLogCacheImpl.Java  需要用到

第三步:建一个实体类  UserLogCache.java

package com.xrq.example.bean;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.util.Date;

/**
 * @author XuRuiQing
 * @date 2018/10/15 15:50
 */
@Entity
public class UserLogCache {
    @Id
    @GeneratedValue
    private Integer id;

    @Column
    private Date date;

    @Column
    private String name;

    @Column
    private String address;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "RoncooUserLog [id=" + id + ", createTime=" + date + ", userName=" + name + ", address=" + address + "]";
    }
}

第四步:先建一个接口 UserCache.java

package com.xrq.example.cache;

import com.xrq.example.bean.UserLogCache;

import java.util.Optional;

/**
 * @author XuRuiQing
 * @date 2018/10/15 15:29
 * ehcache 缓存
 */
public interface UserCache {
    /**
     * 查询
     *
     * @param id
     * @return
     */
    UserLogCache selectById(Integer id);

    /**
     * 更新
     *
     * @param userLogCache
     * @return
     */
    UserLogCache updateById(UserLogCache userLogCache);

    /**
     * 删除
     *
     * @param id
     * @return
     */
    String deleteById(Integer id);
}

再建一个接口 UserDaoCache.java

package com.xrq.example.dao;

import com.xrq.example.bean.UserLogCache;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

/**
 * @author XuRuiQing
 * @date 2018/10/16 11:34
 */
public interface UserDaoCache extends JpaRepository<UserLogCache,Integer>{

    @Query(value="select u from UserLogCache u where u.name=?1")

    UserLogCache findByName(String string);

    UserLogCache findByNameAndAddress(String string, String address);

    Page<UserLogCache> findByName(String string, Pageable pageable);
}

第五步:建一个实现类UserLogCacheImpl.java

package com.xrq.example.cache.impl;

import com.xrq.example.bean.UserLogCache;
import com.xrq.example.cache.UserCache;
import com.xrq.example.dao.UserDaoCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;


/**
 * @author XuRuiQing
 * @date 2018/10/15 16:03
 */
@CacheConfig(cacheNames = "userLogCache")
@Repository
public class UserLogCacheImpl implements UserCache{

    @Autowired
    private UserDaoCache userCacheDao;

    @Cacheable(key = "#p0")
    @Override
    public UserLogCache selectById(Integer id) {
        System.out.println("查询功能,缓存找不到,直接读库, id=" + id);
        return userCacheDao.findById(id).orElse(null);
    }


    @CachePut(key = "#p0")
    @Override
    public UserLogCache updateById(UserLogCache userLogCache) {
        System.out.println("更新功能,更新缓存,直接写库,id="+userLogCache);
        return userCacheDao.save(userLogCache);
    }

    @CachePut(key = "#p0")
    @Override
    public String deleteById(Integer id) {
        System.out.println("删除功能,删除缓存,直接写库, id=" + id);
        return "清空缓存成功";
    }

}

第六步:建一个Controller类来测试

package com.xrq.example.controller;

import com.xrq.example.bean.UserLogCache;
import com.xrq.example.cache.UserCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;

/**
 * @author XuRuiQing
 * @date 2018/10/16 14:55
 */
@RestController
@RequestMapping("/api")
public class ApiController {

    /**
     * 测试 ehcache缓存
     */
    @Autowired
    private UserCache userCache;

    @CrossOrigin(origins = "http://localhost:8080")
    @RequestMapping(value = "/get")
    public HashMap<String,Object> get(@RequestParam String name){
        HashMap<String,Object> map = new HashMap<>();
        map.put("title","hello world");
        map.put("name",name);
        return map;
    }

    /**
     *测试 OK
     * @param id
     * @return
     */
    @RequestMapping(value = "/select",method = RequestMethod.GET)
    public UserLogCache get(@RequestParam(defaultValue = "1") Integer id){
        return userCache.selectById(id);
    }

    /**
     * 测试 OK
     * @param id
     * @return
     */
    @RequestMapping(value = "/update",method = RequestMethod.GET)
    public UserLogCache update(@RequestParam(defaultValue = "1") Integer id){
        UserLogCache bean = userCache.selectById(id);
        bean.setName("测试2");
        bean.setDate(new Date());
        userCache.updateById(bean);
        return bean;
    }

    /**
     * 测试 OK
     * @param id
     * @return
     */
    @RequestMapping(value = "/del",method = RequestMethod.GET)
    public String del(@RequestParam(defaultValue = "1") Integer id){
        System.out.println(userCache.selectById(id));
        return userCache.deleteById(id);
    }

}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大猩猩爱分享

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值