09蚂蚁-分布式缓存架构——10.Springboot+Redis+Ehcache实现二级缓存

Springboot+Redis+Ehcache实现二级缓存

一定要看懂第二张图,你在查询的时候,一定要记得将值在返回到缓存中去,二级缓存查到,就返回到一级缓存中,数据库查到就缓存到二级缓存再一级缓存

本文实现的是ehcache作为一级缓存,redis作为二级缓存

背景

在这里插入图片描述

逻辑图

在这里插入图片描述

代码部分

1.配置 application.yml

spring:
  #s数据库配置
  datasource:
    url: jdbc:mysql://localhost:3306/jeremy?useSSL=false&serverTimezone=UTC
    username: root
    password: 123
    driver-class-name: com.mysql.cj.jdbc.Driver
  ## redis 配置
  redis:
    database: 0
    host: 47.106.241.205
    port: 6379
    password: 123456
    jedis:
      pool:
        max-active: 8
        max-wait: -1
        max-idle: 8
        min-idle: 0
    timeout: 10000
  ## ehcache配置
  cache:
    type: ehcache
    ehcache:
      config: classpath:app1_ehcache.xml

2.app1_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">

    <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>
    &lt;!&ndash; 配置 rmi 集群模式 -集群监听端口号&ndash;&gt;
    <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>

3.依赖包pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.itmayiedu</groupId>
    <artifactId>redis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>redis</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!-- SpringBoot web 核心组件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--spring boot对redis的支持-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</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>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>



    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>com.itmayiedu.controller.IndexController</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>

            </plugin>
        </plugins>
    </build>

</project>

4.启动类

package com.itmayiedu.redis;

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

@SpringBootApplication
@MapperScan(basePackages = {"com.itmayiedu.redis.mapper"})
@EnableCaching
public class RedisApplication {

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

5.controller包
里面主要是getUserId做一级二级缓存的,请测试这个方法。其他不是

package com.itmayiedu.redis.controller;

import com.itmayiedu.redis.entity.User;
import com.itmayiedu.redis.server.RedisServer;
import com.itmayiedu.redis.server.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class IndexController {
    @Autowired
    private RedisServer redisServer;
    @Autowired
    private UserService userService;
    @RequestMapping("/setString")
    public String setString(String key,String object){
        redisServer.set(key,object,60l);
        return "success";
    }
    @RequestMapping("getString")
    public String getString(String key){
        return redisServer.getString(key);
    }

    @RequestMapping("/getUserId")
    public User getUserId(Long id){
        return userService.getUser(id);
    }
}

6.service包

package com.itmayiedu.redis.server;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.itmayiedu.redis.entity.User;
import com.itmayiedu.redis.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class UserService {

    @Autowired
    private EhCacheUtils ehCacheUtils;
    @Autowired
    private RedisServer redisServer;
    @Autowired
    private UserMapper userMapper;
    private String cacheName = "userCache";

    public User getUser(Long id){
        //1.先查询一级缓存 key是以当前的类名+方法名称+id+参数值FD
        String key = this.getClass().getName()+"-"+Thread.currentThread().getStackTrace()[1].getMethodName()
                +"-id:"+id;
        //1.1查询一级缓存数据有对应的值存在,如果有值直接返回
        User ehuser = (User) ehCacheUtils.get(cacheName,key);
        if(ehuser != null){
            System.out.println("key:"+key+",直接从一级缓存获取数据:user:"+ehuser.toString());
            return ehuser;
        }
        //1.1查询一级缓存数据没有有对应的值存在,直接查询redis redis中如何存放对象呢?json格式
        //2.查询二级缓存
        String userJson = redisServer.getString(key);
        //如果redis缓存中有这个对应的值,修改一级缓存
        if(!StringUtils.isEmpty(userJson)){
            JSONObject jsonObject= new JSONObject();
            User resultUser = jsonObject.parseObject(userJson, User.class);
            //存放一级缓存
            ehCacheUtils.put(cacheName,key,resultUser);
            return resultUser;
        }
        //3.查询db
        User user = userMapper.getUser(id);
        if(user == null){
            return null;
        }
        //存放二级缓存redis
        redisServer.setString(key,new JSONObject().toJSONString(user));
        //存放一级缓存
        ehCacheUtils.put(cacheName,key,user);
        //一级缓存的有效时间减去二级缓存执行代码时间
        return user;
    }
}

7.EhCacheUtil

package com.itmayiedu.redis.server;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

//springboot 整合redis
@Component
public class RedisServer {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void set(String key,Object object,Long time){

        //让该方法能够支持多种数据类型存放
        if(object instanceof String){ //如果是String类型的数据
            setString(key,object);
        }
        //如果存放Set类型
        if(object instanceof Set){
            setSet(key,object);
        }
        if(object instanceof List){
            setList(key,object);
        }
        //设置有效期
        if(time!=null){
            stringRedisTemplate.expire(key,time, TimeUnit.SECONDS);
        }
    }


    public void setString(String key,Object object){
        //开启事务权限
        stringRedisTemplate.setEnableTransactionSupport(true);
        try{
            //开启事务 begin
            stringRedisTemplate.multi();
            String value = (String) object;
            //存放String 类型
            stringRedisTemplate.opsForValue().set(key,value);
            //提交事务
            stringRedisTemplate.exec();
        }catch (Exception e){
            //回滚
            stringRedisTemplate.discard();
        }

    }

    public String getString(String key){
        return stringRedisTemplate.opsForValue().get(key);
    }

    public void setSet(String key,Object object){
        Set<String> valueSet = (Set<String>) object;
        for(String string : valueSet){
            stringRedisTemplate.opsForSet().add(key,string);
        }
    }
    private void setList(String key, Object object) {
        List<String> valueList = (List<String>) object;
        stringRedisTemplate.opsForList().leftPushAll(key,valueList);
    }

}

8.redisServer

package com.itmayiedu.redis.server;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

//springboot 整合redis
@Component
public class RedisServer {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void set(String key,Object object,Long time){

        //让该方法能够支持多种数据类型存放
        if(object instanceof String){ //如果是String类型的数据
            setString(key,object);
        }
        //如果存放Set类型
        if(object instanceof Set){
            setSet(key,object);
        }
        if(object instanceof List){
            setList(key,object);
        }
        //设置有效期
        if(time!=null){
            stringRedisTemplate.expire(key,time, TimeUnit.SECONDS);
        }
    }


    public void setString(String key,Object object){
        //开启事务权限
        stringRedisTemplate.setEnableTransactionSupport(true);
        try{
            //开启事务 begin
            stringRedisTemplate.multi();
            String value = (String) object;
            //存放String 类型
            stringRedisTemplate.opsForValue().set(key,value);
            //提交事务
            stringRedisTemplate.exec();
        }catch (Exception e){
            //回滚
            stringRedisTemplate.discard();
        }

    }

    public String getString(String key){
        return stringRedisTemplate.opsForValue().get(key);
    }

    public void setSet(String key,Object object){
        Set<String> valueSet = (Set<String>) object;
        for(String string : valueSet){
            stringRedisTemplate.opsForSet().add(key,string);
        }
    }
    private void setList(String key, Object object) {
        List<String> valueList = (List<String>) object;
        stringRedisTemplate.opsForList().leftPushAll(key,valueList);
    }

}

9.userMapper

package com.itmayiedu.redis.mapper;

import com.itmayiedu.redis.entity.User;
import org.apache.ibatis.annotations.Select;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;

//@CacheConfig配置缓存基本信息 cacheNames缓存名称
//@Cacheable 该方法查询数据库完毕之后,存入到缓存中

@CacheConfig(cacheNames = {"userCache"}) //配置缓存的基本信息
public interface UserMapper {
    @Select("SELECT ID,NAME,AGE from ehcacheTest where id = #{id}")
    @Cacheable
    User getUser(Long id);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值