SpringBoot集成JetCache做缓存

文章目录

    • JetCache了解
    • 代码入门

SpringBoot使用Mybatis的二级缓存,可以采用redis方案。实际有更复杂的应用场景,有些数据我打算永久有效或者过期时间是24小时;为了考虑更好的可靠性,缓存方案采用本地服务器缓存加远程Redis方案。这些Mybatis缓存接口都是无法满足。最后找到了一个解决方案JetCache。本文就是集成JetCache的一个例子。

JetCache了解

https://github.com/alibaba/jetcache
中文版本:
https://github.com/alibaba/jetcache/wiki/Home_CN

文档目录

  • 基本Cache
  • API 通过@CreateCache注解创建Cache实例
  • 通过注解实现方法缓存
  • 配置详解
  • 高级Cache API
  • Redis支持(两种redis客户端二选一即可)
    • 使用jedis客户端连接redis
    • 使用lettuce客户端连接redis
  • 内存缓存LinkedHashMapCache和CaffeineCache
  • 统计

代码入门

示例代码,不必纠结规范。
pom.xml关键配置。

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alicp.jetcache/jetcache-starter-redis -->
        <dependency>
            <groupId>com.alicp.jetcache</groupId>
            <artifactId>jetcache-starter-redis</artifactId>
            <version>2.6.0.RC</version>
        </dependency>


    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <compilerArgs>
                        <arg>-parameters</arg>
                    </compilerArgs>
                </configuration>
            </plugin>
        </plugins>
    </build>

package com.example.demo.controller;

import com.example.demo.entities.UserInfo;
import com.example.demo.mapper.UserInfoMapper;
import com.example.demo.service.UserInfoCreateCacheService;
import com.example.demo.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserInfoCreateCacheService userInfoCreateCacheService;

    @RequestMapping("/")
    public String  hello(){
        return "欢迎!!!";
    }

    @RequestMapping("/getid")
    public String  getbyid(@RequestParam Long id){
        long begl=System.currentTimeMillis();

        UserInfo user = new UserInfo();
        user = userInfoService.selectById(id);

        long edl=System.currentTimeMillis();
        System.out.println("花费时间"+ (edl-begl) + " 用户信息 " + user);

        return "花费时间"+ (edl-begl) + " 用户信息 " + user;
    }

    @RequestMapping("/getidc")
    public String  getbyidc(@RequestParam Long id){

        long begl=System.currentTimeMillis();

        UserInfo user = new UserInfo();

        user = userInfoCreateCacheService.selectByIdC(id);

        long edl=System.currentTimeMillis();
        System.out.println("花费时间"+ (edl-begl) + " 用户信息 " + user);

        return "花费时间"+ (edl-begl) + " 用户信息 " + user;
    }
}

package com.example.demo.entities;


import java.io.Serializable;

public class UserInfo implements Serializable
{
    private long userId;

    private String userName;

    private int userAge;

    private  String label;

    public UserInfo(){

    }
    public UserInfo(long userId,String userName,int userAge,String label) {
        this.userId = userId;
        this.userName = userName;
        this.userAge = userAge;
        this.label = label;
    }

    public long getUserId() {
        return userId;
    }

    public void setUserId(long userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public int getUserAge() {
        return userAge;
    }

    public void setUserAge(int userAge) {
        this.userAge = userAge;
    }

    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }
}

package com.example.demo.mapper;

import com.example.demo.entities.UserInfo;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;


@Mapper
@Component
public interface UserInfoMapper {

    UserInfo selectById(Long userId);
}

package com.example.demo.service;

import com.example.demo.entities.UserInfo;

public interface UserInfoCreateCacheService {

    UserInfo selectByIdC(long userId);
}
package com.example.demo.service;

import com.example.demo.entities.UserInfo;

public interface UserInfoService {

    UserInfo selectById(long userId);
}
package com.example.demo.serviceimpl;

import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.CreateCache;
import com.example.demo.entities.UserInfo;
import com.example.demo.mapper.UserInfoMapper;
import com.example.demo.service.UserInfoCreateCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class UserInfoCreateCacheServiceImpl implements UserInfoCreateCacheService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    //name后缀增加冒号,key自动归类;
    @CreateCache(name = "UserInfoCreateCacheService_selectByIdC:", expire = 3600, cacheType = CacheType.REMOTE, localLimit = 50)
    private Cache<Long, UserInfo> userCache;
//自定义一个缓存,然后进行操作。
    //可自定义比较灵活
    @Override
    public UserInfo selectByIdC(long userId) {

        UserInfo user = userCache.get(userId);
        if (user != null) {
            return user;
        }else{
            user = userInfoMapper.selectById(userId);
            userCache.put(userId, user,10, TimeUnit.MINUTES);
           // HashMap<Long,UserInfo>  map= new HashMap<Long,UserInfo>();
           // map.put(userId, user);
           // userCache.putAll(map);
        }
        return user;
    }
}

key使用Spring的SpEL脚本来指定。如果要使用参数名(比如这里的key="#userId"),项目编译设置target必须为1.8格式, 并且指定javac的-parameters参数,否则就要使用key="args[0]"这样按下标访问的形式。
保留参数名这一选项由编译开关javac -parameters打开,则:参数名称被编译进了class文件。
保留参数名这一选项由编译开关javac -parameters关闭,则:参数名称是无意义的org0、org1…
参考文章:https://blog.csdn.net/qq_34169240/article/details/78340275

package com.example.demo.serviceimpl;

import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.Cached;
import com.example.demo.entities.UserInfo;
import com.example.demo.mapper.UserInfoMapper;
import com.example.demo.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl  implements UserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * key使用Spring的SpEL脚本来指定。如果要使用参数名(比如这里的key="#userId"),项目编译设置target必须为1.8格式,
     * 并且指定javac的-parameters参数,否则就要使用key="args[0]"这样按下标访问的形式。
     * 采用pom方式配置-parameters参数
     * @param userId
     * @return
     */
    @Override
    @Cached(name="UserInfoService.selectById:",key ="#userId" ,expire = 3600,cacheType = CacheType.REMOTE)
    //方法级别包扫描,需要这样配置@EnableMethodCache(basePackages = "com.example.demo")
    //或者@EnableMethodCache(basePackages = "com.example.demo.serviceimpl")
    //不能配置在接口包下,必须是实现包下
    public UserInfo selectById(long userId) {
        UserInfo user = userInfoMapper.selectById(userId);

        return user;
    }
}

package com.example.demo;

import com.alicp.jetcache.anno.config.EnableCreateCacheAnnotation;
import com.alicp.jetcache.anno.config.EnableMethodCache;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan(basePackages = "com.example.demo.mapper")
@EnableMethodCache(basePackages = "com.example.demo.serviceimpl")
@EnableCreateCacheAnnotation
public class SpringbootRediscacheApplication {

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

}

缓存到Redis的结果信息:
SpringBoot集成JetCache做缓存_第1张图片

你可能感兴趣的:(#)