SpingBoot(六)——整合Redis

SpringBoot 版本号 2.1.3
GitHub项目地址

  1. 导入场景启动器

    <dependency>			<groupId>org.springframework.boot</groupId>
    	<artifactId>
            spring-boot-starter-data-redis
        </artifactId>
    </dependency>
    
  2. 配置yml

      redis:
        host: 192.168.1.120
    
  3. 使用注解缓存

    @MapperScan("com.springboot.redis.dao")
    @SpringBootApplication
    @EnableCaching//开启缓存注解
    public class SpringBootIntegrationRedisApplication {
    
    	public static void main(String[] args) {
    		SpringApplication.run(SpringBootIntegrationRedisApplication.class, args);
    	}
    
    }
    /**
    *  在service即可使用
    *@CacheConfig(cacheNames = "uer")
    * @Cacheable(key = "#userId")
    *@CachePut(key = "#user.userId")
    *@CacheEvict(key = "#userId")
    */
    

    注解版不可自定义配置缓存时间;默认以2进制存储,redis中乱码

  4. 使用RedisTemplate进行操作

    不用再开启注解

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class SpringBootIntegrationRedisApplicationTests {
    
    	@Autowired
    	UserDao userDao;
    
    	@Autowired
    	StringRedisTemplate stringRedisTemplate;//key-value都是字符串
    	@Autowired
    	RedisTemplate redisTemplate; //key-value都是对象
    
    	@Autowired
    	RedisTemplate <Object,Object> myredisTemplate;
    
    	/**
    	 * Redis常见的五大数据类型
    	 *  String(字符串)、List(列表)、Set(集合)、Hash(散列)、ZSet(有序集合)
    	 *  stringRedisTemplate.opsForValue()[String(字符串)]
    	 *  stringRedisTemplate.opsForList()[List(列表)]
    	 *  stringRedisTemplate.opsForSet()[Set(集合)]
    	 *  stringRedisTemplate.opsForHash()[Hash(散列)]
    	 *  stringRedisTemplate.opsForZSet()[ZSet(有序集合)]
    	 */
    
    	/**
    	 * String
    	 */
        @Test
    	@Ignore
    	public void test01(){
        	//存
        	stringRedisTemplate.opsForValue().append("key01","value-String");
        	//取
             String msg=stringRedisTemplate.opsForValue().get("key01");
             System.out.println(msg);
    
    	}
    
    	/**
    	 * 集合操作
    	 */
    	@Test
    	@Ignore
    	public void test02(){
        	//存
        	stringRedisTemplate.opsForList().leftPush("keyList","1");
    		stringRedisTemplate.opsForList().leftPush("keyList","2");
    		//取
    //		String value=stringRedisTemplate.opsForList().leftPop("keyList");
    //		System.out.println(value);
    	}
    
    	@Test
    	@Ignore
    	public void  test03(){
        	User user=userDao.findByUserId(1);
        	redisTemplate.opsForValue().set("user-01",user);
    	}
    
    	/**
    	 * 默认序列化器下 使用json存储对象
    	 */
    	@Test
        @Ignore
    	public void  test04(){
    		User user=userDao.findByUserId(1);
            System.out.println(user);
            JSONObject.fromObject(user);
            redisTemplate.opsForValue().set("json-01",JSONObject.fromObject(user).toString());
    	}
    
    	/**
    	 * 根据自定义的序列化模板存储对象
    	 */
    	@Test
    	@Ignore
    	public void test05() {
    		User user=userDao.findByUserId(1);
    		myredisTemplate.opsForValue().set("user-001",user);
    	}
    
    	/**
    	 * 获取通过key获取对象类型值
    	 */
    	@Test
    	@Ignore
        public void test06(){
    	User user= (User) myredisTemplate.opsForValue().get("user-001");
          System.out.println(user);
         }
    
    	/**
    	 * 删除操作
    	 */
    	@Test
        public void test(){
    		myredisTemplate.delete("user-001");
        }
    	/**
    	 * 设置时间
    	 */
    	@Test
    	@Ignore
         public  void test07(){
    		 stringRedisTemplate.opsForValue().set("time","10s",10, TimeUnit.SECONDS);
    	 }
    }
    
    

    配置序列化器

    @Configuration
    public class MyRedisConfig {
    
        /**
         * redisTemplate 序列化使用的jdkSerializeable, 存储二进制字节码, 所以自定义序列化类
         * @param redisConnectionFactory
         * @return
         */
        @Bean
        public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
            RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
            redisTemplate.setConnectionFactory(redisConnectionFactory);
            // 使用Jackson2JsonRedisSerialize 替换默认序列化
            Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
            objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
            jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
            // 设置value的序列化规则和 key的序列化规则
            redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
            redisTemplate.setKeySerializer(new StringRedisSerializer());
            redisTemplate.afterPropertiesSet();
            return redisTemplate;
        }
        @Bean
        public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
            RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                    .entryTtl(Duration.ofSeconds(20)); // 设置整体缓存有效期一小时
            return RedisCacheManager
                    .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
                    .cacheDefaults(redisCacheConfiguration).build();
        }
    
    
    }
    
    

    在没有单个时间限制的情况下还是注解更方便;若全局时间一样可通过cacheManage统一管理(两个时间都设置了以opsForValue().set()中的时间为准)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值