springboot 整合 redis + @cacheAble

 

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

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

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

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

3、第一次访问接口/get  会进入 Cacheable 有请求过来,之后就没有打印

 

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<Object, Object> empRedisTemplate(RedisConnectionFactory redisConnectionFactory)
        throws Exception {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        // Json序列化配置
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<Object>(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
  <!--mapperScan包-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.0</version>
        </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>
            <scope>runtime</scope>
        </dependency>
        <!--cacheable-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <!--redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

后端从入门到精通

你的鼓励是我最大的动力~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值