SpringBoot整合Ehcache框架

SpringBoot整合Ehcache框架

1.创建数据库

-- database test
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

SET FOREIGN_KEY_CHECKS = 1;

2.创建一个SpringBoot项目

项目结构

在这里插入图片描述

3.添加依赖

pom.xml

        <!-- SpringBoot 对lombok 支持 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>

        <!-- SpringBoot 外部tomcat支持 -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>

        <!-- springboot-log4j -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j</artifactId>
            <version>1.3.8.RELEASE</version>
        </dependency>

        <!-- springboot-aop 技术 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-lang/commons-lang -->
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </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>
            <version>2.9.1</version><!--$NO-MVN-MAN-VER$ -->
        </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>

        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
    </dependencies>
</project>

4.编写配置文件

application.yml

###端口号配置
server:
  port: 8080
###数据库配置
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
    test-while-idle: true
    test-on-borrow: true
    validation-query: SELECT 1 FROM DUAL
    time-between-eviction-runs-millis: 300000
    min-evictable-idle-time-millis: 1800000
  # 缓存配置读取
  cache:
    type: ehcache
    ehcache:
      config: classpath:ehcache1.xml

ehcache1.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">

    <diskStore path="java.io.tmpdir/ehcache-rmi-4000" />

    <!-- 多台机器配置 rmiUrls=//192.168.8.32:400002/demoCache|//192.168.5.231:400003/demoCache -->
    <cacheManagerPeerProviderFactory
            class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
            properties="peerDiscovery=manual,rmiUrls=//127.0.0.1:5000/userCache">
    </cacheManagerPeerProviderFactory>
    <!-- 配置 rmi 集群模式 -->
    <cacheManagerPeerListenerFactory
            class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"
            properties="hostName=127.0.0.1,port=4000,socketTimeoutMillis=120000" />

    <!-- 多播方式配置 搜索某个网段上的缓存 timeToLive 0是限制在同一个服务器 1是限制在同一个子网 32是限制在同一个网站 64是限制在同一个region
        128是限制在同一个大洲 255是不限制 <cacheManagerPeerProviderFactory class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
        properties="peerDiscovery=automatic, multicastGroupAddress=224.1.1.1, multicastGroupPort=40000,
        timeToLive=32" /> -->

    <!-- 默认缓存 -->
    <defaultCache maxElementsInMemory="1000" eternal="true"
                  timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true"
                  diskSpoolBufferSizeMB="30" maxElementsOnDisk="10000000"
                  diskPersistent="true" diskExpiryThreadIntervalSeconds="120"
                  memoryStoreEvictionPolicy="LRU">
    </defaultCache>

    <!-- demo缓存 -->
    <cache name="userCache" maxElementsInMemory="1000" eternal="false"
           timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true"
           diskSpoolBufferSizeMB="30" maxElementsOnDisk="10000000"
           diskPersistent="false" diskExpiryThreadIntervalSeconds="120"
           memoryStoreEvictionPolicy="LRU">
        <cacheEventListenerFactory
                class="net.sf.ehcache.distribution.RMICacheReplicatorFactory" />
        <!-- 用于在初始化缓存,以及自动设置 -->
        <bootstrapCacheLoaderFactory
                class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory" />
    </cache>
</ehcache>

5.添加实体类

User.java

package com.ehcache.entity;
import lombok.Data;
import java.io.Serializable;
@Data
public class User implements Serializable {
    private static final long serialVersionUID = 2182708815611071614L;
    private Long id;
    private String name;
    private Integer age;
}

6.添加mapper

UserMapper.java

package com.ehcache.mapper;

import com.ehcache.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import java.util.List;

@Mapper
@Component
@CacheConfig(cacheNames = "userCache") //配置缓存基本信息,缓存名称
public interface UserMapper {
    @Select("SELECT * FROM user where id=#{id}")
    @Cacheable // 该方法查询数据库完毕之后,存入到缓存中
    List<User> getUser(@Param("id") Long id);
}

7.添加service

UserService.java

package com.ehcache.service;

import com.ehcache.entity.User;
import java.util.List;

public interface UserService {
    /**
     * 获取用户信息
     * @param id
     * @return
     */
    public List<User> getUser(Long id);
}

UserServiceImpl.java

package com.ehcache.service.impl;

import com.ehcache.entity.User;
import com.ehcache.mapper.UserMapper;
import com.ehcache.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;
    /**
     * 根id据获取用户信息
     * @param id
     * @return
     */
    @Override
    public List<User> getUser(Long id) {
        return userMapper.getUser(id);
    }
}

8.添加MapCache

MapCache.java

package com.ehcache.ehcache;

import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class MapCache<K, V> {

    //存放缓存容器
    public Map<K, V> concurrentHashMap = new ConcurrentHashMap<K, V>();

    //纯手写单个JVM缓存框架 缓存概念偏向于临时 如何设置时间有限期 2个线程
    //白话文代码分析 容器MAP集合

    //存储
    public void put(K k, V v){
        concurrentHashMap.put(k, v);
    }

    //查询
    public V get(K k){
        return concurrentHashMap.get(k);
    }

    //删除
    public void remove(K k){
        concurrentHashMap.remove(k);
    }
}

9.编写Controller

IndexControoller.java

package com.ehcache.api.controller;

import com.ehcache.ehcache.MapCache;
import com.ehcache.entity.User;
import com.ehcache.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class IndexControoller {

    @Autowired
    private MapCache<String, Object> mapCache;
    @Autowired
    private UserService userService;
    @Autowired
    private CacheManager cacheManager;

    /**
     * 清理缓存
     */
    @RequestMapping("/remoKey")
    public void remoKey() {
        cacheManager.getCache("userCache").clear();
    }

    @RequestMapping("/getUser")
    @ResponseBody
    public List<User> getUser(Long id){
        return userService.getUser(id);
    }

    @RequestMapping("/get")
    @ResponseBody
    public String get(String key){
        return (String) mapCache.get(key);
    }

    @RequestMapping("/put")
    @ResponseBody
    public String get(String key, String value){
        mapCache.put(key, value);
        return "success";
    }

    @RequestMapping("/remove")
    @ResponseBody
    public String remove(String key){
        mapCache.remove(key);
        return "success";

    }
}

10.给EhcacheApplication启动类添加注解

package com.ehcache;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching //开启缓存
public class EhcacheApplication {

    public static void main(String[] args) {
        SpringApplication.run(EhcacheApplication.class, args);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值