springboot 整合 redis + @cacheAble

发布时间:2023-01-29 21:00

 

注意启动类要上加@EnableCaching注解

1、写一个redisConfig,吧cacheable的缓存指定到redis里

2、servie层加@Cacheable(value = "user_cache", key = "#uid", unless="#result == null")

unless="#result == null表示结果为null不缓存

3、第一次访问接口/get  会进入 Cacheable 有请求过来,之后就没有打印springboot 整合 redis + @cacheAble_第1张图片

 

4、后面直接从缓存获取,如图

5、可以配合spring表达式使用:

package com.alibaba.first.controller.cache;

/**
 * @author keying
 * @date 2021/4/28
 */
public class CacheName {

    public final static  String USER_CACHE = "USER_CACHE";

    public final static  String USER_CACHE2 = "USER_CACHE2";
}
    @Cacheable(value = {CacheName.USER_CACHE}, key = "T(com.alibaba.first.controller.cache.CacheName).USER_CACHE2 +'_'+ #uid", unless="#result == null")


import java.time.Duration;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author keying
 * @date 2021/4/9
 */
@Configuration
@EnableCaching
public class RedisCacheConfig {
    @Bean
    public RedisTemplate empRedisTemplate(RedisConnectionFactory redisConnectionFactory)
        throws Exception {
        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        // Json序列化配置
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
        template.setDefaultSerializer(serializer);
        return template;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofSeconds(600))  //存入Redis的时间设置600秒
            //.entryTtl(Duration.ofDays(1))
            .disableCachingNullValues()
            .serializeKeysWith(RedisSerializationContext.SerializationPair
                .fromSerializer(new StringRedisSerializer()))
            .serializeValuesWith(
                RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
        return RedisCacheManager.builder(factory).cacheDefaults(cacheConfiguration).build();
    }
}
 
  

import com.alibaba.first.mapper.UserMapper;
import com.alibaba.first.model.User;
import com.alibaba.first.service.CacheService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author keying
 * @date 2021/4/9
 */
@Service
public class CacheServicelmpl implements CacheService {

    @Autowired
    private UserMapper userMapper;

    @Override
    @Cacheable(value = "user_cache", key = "#uid", unless="#result == null")
    public User getUserDetailsByUid(Integer uid) {
        System.out.println(" Cacheable 有请求过来了");
        User user = userMapper.getUser(uid);
        return user;
    }

    @Override
    @CachePut(value = "user_cache", key = "#user.uid")
    public User updateUser(User user) {
        System.out.println(" update 有请求过来了");
        if(userMapper.updateUser(user) > 0) {
            // 这里也可以直接在updateByPrimaryKeySelective的方法里,修改后直接查询出该记录返回UserDetails实例,看需求。
           /* user = userMapper.getUser(user.getUid());*/
            return user;
        }else{
            return null;
        }
    }

}


import java.io.Serializable;

import lombok.*;

/**
 * 用户
 *
 * @author keying
 * @date 2021/3/19
 */
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@ToString
public class User implements Serializable {

    private Integer uid;

    private String name;

    private Integer age;
}



import com.alibaba.first.model.User;
import com.alibaba.first.service.CacheService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author keying
 * @date 2021/4/9
 */
@RestController
@RequestMapping(value = "/cache")
public class CacheController {

    @Autowired
    private CacheService cacheService;

    @RequestMapping(value = "/get")
    public User getUserDetailsByUid(Integer uid){
        try {
            return cacheService.getUserDetailsByUid(uid);
        }catch (Exception e){
            System.out.println(e.toString());
            return null;
        }
    }

    @RequestMapping(value = "/update")
    public int updateUserInfo(Integer uid, String name){
        User user = new User();
        user.setUid(uid);
        user.setName(name);
        user = cacheService.updateUser(user);
        return user == null ? 0 : user.getUid();
    }

}
spring.thymeleaf.cache=false

#
server.servlet.session.timeout:3600
server.port=8181

#
logging.level.com.keying.dao=DEBUG

#mybatis
#mybatis.config-location=classpath:config/mybatis-conf.xml
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.first.model
#mybatis.configuration.map-underscore-to-camel-case=true

#spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.url=jdbc:mysql://localhost:3306/testmac?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

# ----- Redis -------- #
# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=0  
# Redis服务器地址
spring.redis.host=127.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8  
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1  
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8  
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0  
# 连接超时时间(毫秒)
spring.redis.timeout=5000
  
        
            org.mybatis
            mybatis-spring
            2.0.0
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.1.1
        
        
        
            mysql
            mysql-connector-java
            runtime
        
        
        
            org.springframework.boot
            spring-boot-starter-cache
        
        
        
            org.springframework.boot
            spring-boot-starter-data-redis
        

ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号