SpringBoot2.0整合ehcache實現單點項目緩存

使用SpringBoot2.0整合ehcache實現單點項目緩存

1.創建一個springboot項目,在pom.xml中引入相關依賴

       <!-- SpringBoot 對lombok 支持 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!--開啓 cache 緩存 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <!-- ehcache緩存 -->
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
        <!-- mysql 依賴 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

2.創建一個ehcache配置文件ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">

    <!--這個是磁盤存儲路徑,當內存緩存滿了的時候,就會存放在此處-->
    <diskStore path="java.io.tmpdir"/>

    <!--defaultCache:echcache的默認緩存策略  -->
    <defaultCache maxElementsInMemory="10000" eternal="false"
                  timeToIdleSeconds="120"
                  timeToLiveSeconds="120"
                  maxElementsOnDisk="10000000"
                  diskExpiryThreadIntervalSeconds="120"
                  memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>
        <!--此處的user與後面緩存名稱一致-->
    <cache name="user"
           maxElementsInMemory="10000"
           eternal="false"
           timeToIdleSeconds="120"
           timeToLiveSeconds="120"
           maxElementsOnDisk="10000000"
           diskExpiryThreadIntervalSeconds="120"
           memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </cache>
</ehcache>

3.在application.yml文件中添加相關配置

###端口號配置
server:
  port: 8080
###數據庫配置  
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
  # 緩存配置讀取
  cache:
    type: ehcache
    ehcache:
      config: classpath:ehcache.xml

4.在啓動類上添加開始緩存的註解


@MapperScan(basePackages = {"com.gothic.ehcache.mapper"})
@EnableCaching   //開啓緩存
@SpringBootApplication
public class EhcacheApplication {

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

}

5.創建一個用戶對象

@Data
public class Users implements Serializable {

    private Integer id;
    private String name;
    private Integer age;

}

6.在控制器中實現查詢用戶以及修改用戶

@RestController
public class IndexControoller {

    @Autowired
    private UserService userService;
    
    /**
     * @Description: 查詢用戶
     */
    @RequestMapping("/getUser")
    public List<Users> getUser(Integer id) {
        return userService.getUser(id);
    }

    /**
     * @Description: 修改用戶,這裏使用測試數據,
     * 不用創建頁面那麼麻煩了
     */
    @GetMapping("/editUser")
    public String editUser(){
        Users users = new Users();
        users.setId(1);
        users.setName("hello");
        users.setAge(32);
        Integer result = userService.editUser(users);
        return "success";
    }
}

7.業務層service

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CacheManager cacheManager;

    public List<Users> getUser(Integer id) {
        return userMapper.getUser(id);
    }

    @Transactional
    public Integer editUser(Users users) {
        Integer result = userMapper.editUser(users);
        //在編輯用戶時,清除查詢用戶的緩存
        cacheManager.getCache("user").clear();
        return result;
    }
}

8.mapper層直接使用註解方式查詢以及編輯,不使用配置文件

//@CacheConfig 配置緩存基本信息cacheName緩存名稱
@CacheConfig(cacheNames = {"user"})
public interface UserMapper {

    //@Cacheable 該方法查詢數據庫完成後,存入到緩存中
    @Select("SELECT ID ,NAME,AGE FROM users where id=#{id}")
    @Cacheable
    List<Users> getUser(@Param("id") Integer id);


    @Update("update users set name=#{name}, age=#{age} where id=#{id}")
    Integer editUser(Users users);
}

9.在數據庫內置一條數據,如下:

10.測試:

①第一次查詢用戶,顯示如下json數據,直接使用MySQL的可視化工具修改該數據的name以及age後再次刷新,依然沒有變化,說明緩存已經生效

②因爲我們在生產過程中不可能去修改數據庫,所以我們爲了在修改數據後實時更新緩存,就需要在編輯用戶時,清除緩存,就如以上service中的editUser方法中一樣清除,訪問修改用戶的方法

修改成功後再次訪問查詢用戶方法,數據已經更新爲修改後的數據

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章