Spring boot整合redis

SpringBoot引入redis

1. 引入依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--实现FastJson序列化需要引入-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.60</version>
</dependency>
2. 配置yml
spring:
  redis:
    port: 6379 #端口号(默认6379)
    host: 192.168.2.128
    password: 123456
    timeout: 20 #连接超时时间(毫秒)
    jedis:
      pool:
        max-active: 8 #连接池最大连接数(默认8)
        min-idle: 0 #最小空闲连接(默认0)
        max-wait: -1 #最大阻塞等待时间,负值表示没有限制(默认-1ms)
        max-idle: 8 #最大空闲连接(默认8)
3. 在springboot启动类上加上@EnableCaching注解
/**
 * 一.搭建基本环境
 * 1.导入数据库文件 创建出employee表
 * 2.创建javaBean封装数据
 * 3.整合MyBatis操作数据库
 *      1.配置数据源信息
 *      2.使用注解版的MyBatis
 *        1)@MapperScan指定需要扫描的mapper接口所在的包
 * 二.快速体验缓存
 *    步骤:
 *      1.开启基于注解的缓存 @EnableCaching
 *      2.标注缓存注解即可
 *        @Cacheable 将方法的运行结果进行缓存
 *        @CacheEvict
 *        @CachePut
 *
 *  运行流程:
 *  @Cacheable:
 *  1、方法运行之前,先去查询Cache(缓存组件),按照cacheNames指定的名字获取;
 *      (CacheManager先获取相应的缓存),第一次获取缓存如果没有Cache组件会自动创建。
 *  2、去Cache中查找缓存的内容,使用一个key,默认就是方法的参数;
 *      key是按照某种策略生成的;默认是使用keyGenerator生成的,默认使用SimpLekeyGenerator生成key;
 *         SimplekeyGenerator生成key的默认策略;
 *              如果没有参数;key=new Simplekey();
 *              如果有一个参数:key=参数的值
 *              如果有多个参数:key=new Simplekey(params);
 *  3、没有查到缓存就调用目标方法
 *  4、将目标方法返回的结果,放进缓存中
 *  @CacheabLe标注的方法执行之前先来检查缓存中有没有这个数据,默认按照参数的值作为key去查询缓存,
 *  如果没有就运行方法并将结果放入缓存;以后再来调用就可以直接使用缓存中的数据;
 *  
 * @author Manaphy
 */
@MapperScan("com.cgp.cache.mapper")
@SpringBootApplication
@EnableCaching
public class SpringbootCacheApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootCacheApplication.class, args);
    }
}
配置序列化方式(FastJson)
import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.cache.CacheManager;
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.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;
import java.time.Duration;

/**
 * 将redis数据以json方式序列化
 *
 * @author Manaphy
 * @date 2019-11-27
 */
@Configuration
@SuppressWarnings("unchecked")
public class RedisConfig {

    @Resource
    private RedisConnectionFactory redisConnectionFactory;

    private StringRedisSerializer stringSerializer = new StringRedisSerializer();

    private GenericFastJsonRedisSerializer fastJsonRedisSerializer = new GenericFastJsonRedisSerializer();

    /**
     * 使用redisTemplate方式
     *
     * @return RedisTemplate
     */
    @Bean(name = "redisTemplate")
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        // 注入数据源
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        // key-value结构序列化数据结构
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(fastJsonRedisSerializer);
        // hash数据结构序列化方式,必须这样否则存hash 就是基于jdk序列化的
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);
        // 启用默认序列化方式
        redisTemplate.setEnableDefaultSerializer(true);
        redisTemplate.setDefaultSerializer(fastJsonRedisSerializer);
        return redisTemplate;
    }

    /**
     * 使用注解的方式
     *
     * @param factory RedisConnectionFactory
     * @return CacheManager
     */
    @Bean(name = "cacheManager")
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        // 配置序列化
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(stringSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer))
                .entryTtl(Duration.ofDays(1));//设置过期时间

        return RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
    }
}

4. 在service层中使用注解
/**
 * @author Manaphy
 * @date 2019-07-03 16:37
 */
@Service
//抽取缓存的公共配置
@CacheConfig(cacheNames = "emp")
public class EmployeeService {
    @Resource
    private EmployeeMapper employeeMapper;

    /**
     * @Cacheable几个属性: cacheNames/value:指定缓存组件的名字;将方法的返回结果放在哪个缓存中,是数组的方式,可以指定多个缓存;
     * key:缓存数据使用的key;默认是使用方法参数的值;
     * keyGenerator:key的生成器;可以自己指定key的生成器的组件id
     * key/keyGenerator 二选一使用
     * cacheManager:指定缓存管理器;或者cacheResolver指定获取解析器
     * condition:指定符合条件的情况下才缓存; condition ="#id>0"
     * unless:否定缓存;当unless指定的条件为true,方法的返回值就不会被缓存;可以获取到结果进行判断 unless="#result==null"
     * sync:是否使用异步模式
     */
    @Cacheable(cacheNames = "emp")
    public Employee getEmp(Integer id) {
        System.out.println("查询" + id + "号员工");
        return employeeMapper.getEmpById(id);
    }

    /**
     * @CachePut:既调用方法,又更新缓存数据; 修改了数据库的某个数据, 同时更新缓存;先调用,后缓存
     * key = "#employee.id :使用传入参数的员工的id
     * key = "#result.id" :使用返回后的id
     */
//    @CachePut(value = "emp",key = "#employee.id")
    @CachePut(value = "emp", key = "#result.id")
    public Employee updEmp(Employee employee) {
        System.out.println("updEmp:" + employee);
        employeeMapper.updEmp(employee);
        return employee;
    }


    /**
     * @CacheEvict:缓存清除 key:指定要清除的数据
     * allEntries = true 指定清除这个缓存中所有的数据
     * beforeInvocation=false:默认设置 表示缓存在方法调用之后清除;设置为true后,会在方法调用之前清除
     * 作用:防止方法出现异常从而无法清除缓存
     */
    @CacheEvict(value = "emp", key = "#id")
    public void delEmp(Integer id) {
        System.out.println("delEmp:" + id);
        employeeMapper.delEmpById(id);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值