SpringBoot 1.6 整合Redis

1.6 整合Redis

1.6.1 Redis简介

Redis 是一个完全开源免费的,遵守BSD协议的,具备高性能的key-value数据库。
Redis缓存产品有以下三个特点:

  • Redis支持数据的持久化,可以将内存中的数据保存在磁盘中,重启的时候可以再次加载进行使用。
  • Redis不仅仅支持简单的key-value类型的数据,同时还提供list,set,zset,hash等数据结构的存储。
  • Redis支持数据的备份,即master-slave模式的数据备份。

1.6.2 配置工程

在Spring支持的Redis操作中提供有一个RedisTemplate处理类,利用这个类可以非常方便的实现Redis的各种基本操作。
首先需要修改Pom 文件增加redis依赖:


<!--redis-->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--redis-->

其次修改application-dev.properties配置文件(springboot的主要配置文件为application.yml或application.properties,这里我们以第一个工程的例子为基础进行介绍)。

#==================  redis  ===================#
# redis 单节点地址
spring.redis.host=localhost
# redis 集群
#spring.redis.cluster.nodes=192.168.177.128:7001,192.168.177.128:7002,192.168.177.128:7003
#spring.redis.cluster.max-redirects=3
# Redis 数据库
spring.redis.database=0
# Redis 端口
spring.redis.port=6379
# Redis 密码
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=8 
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=3000

# 其他redis配置可参考网络资源

添加注解配置类,主要用于配置RedisTemplate和CacheManager两个组件。


package com.zone7.admin.config.redis;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zone7.admin.utils.RedisUtil;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.lang.reflect.Method;
import java.time.Duration;

/**
 * RedisConfig
 * Redis配置类
 *
 * @author: zone7
 * @time: 2018.08.20
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {

        RedisTemplate<String, Object> template = new RedisTemplate<>();

        RedisSerializer<String> redisSerializer = new StringRedisSerializer();

        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        template.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //value hashmap序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);

        return template;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

        //解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        // 配置序列化(解决乱码的问题),过期时间30秒
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(30))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();

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


1.6.3 案例开发

下面以RedisTemplate和StringRedisTemaplate的使用为例,介绍redis缓存的应用。RedisTemplate在使用时之需要使用@Autowired引入即可,例如:

@Autowired
RedisTemplate redisTemplate;

这里我们通过开发一个服务层和控制层进行查看redis整合后的效果:
服务层RedisServiceImpl.java 代码

package com.zone7.demo.helloworld.sys.service.impl;

import com.zone7.demo.helloworld.sys.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @ClassName: RedisServiceImpl
 * @Description: redis 案例测试
 * @Author: zgq
 * @Date: 2019/6/19 09:16
 * @Version: 1.0
 */

@Service
public class RedisServiceImpl implements RedisService {
  @Autowired
  private RedisTemplate redisTemplate;
  @Autowired
  private StringRedisTemplate stringRedisTemplate;

  /**
   * 写入
   * @param key
   * @param value
   */
  @Override
  public void put(String key, String value) {
    //redisTemplate.opsForList().leftPush(key, value);
    stringRedisTemplate.opsForValue().set(key,value);
  }

  /**
   * 读取
   * @param key
   * @return
   */
  @Override
  public String get(String key) {
    return stringRedisTemplate.opsForValue().get(key);

  }

}
控制层RedisController.java代码:
package com.zone7.demo.helloworld.sys.controller;

import com.zone7.demo.helloworld.commons.response.ResponseData;
import com.zone7.demo.helloworld.sys.service.RedisService;
import com.zone7.demo.helloworld.sys.service.SysUserService;
import com.zone7.demo.helloworld.sys.vo.SysUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author: zone7
 * @Date: 2019/06/17
 * @Version 1.0
 */
@RestController
@RequestMapping("/redis")
public class RedisController {
    @Autowired
    private RedisService redisService;

    @GetMapping("/put/{key}/{value}")
    public ResponseData put(@PathVariable String key,@PathVariable String value){
        redisService.put(key,value);

        return ResponseData.successMessage("put "+key+"成功");
    }


    @GetMapping("/get/{key}")
    @ResponseBody
    public ResponseData findByName(@PathVariable String key) {
        String value = redisService.get(key);
        return ResponseData.success(value);
    }

}

使用浏览器测试redis服务 的put:
在这里插入图片描述

使用浏览器测试redis服务的get:
在这里插入图片描述
通过redis-cli查看redis存储的内容:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Zone 7

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值