Sprint Boot 集成 Redis  介绍及开发

Redis是一个内存数据存储,可以用作用作数据库,缓存和消息代理。它支持数据结构,例如字符串,哈希,列表,集合,带范围查询的排序集合,位图,日志,带有半径查询和流的地理空间索引。Redis具有内置的复制,Lua脚本,LRU逐出,事务和不同级别的磁盘持久性,并通过Redis Sentinel和Redis Cluster自动分区提供了高可用性。

Spring Boot 集成 Redis 开发 
0. Redis 安装

   这里已经在Linux 下 安装过,所以不必再次安装
    没有安装redis的,需要手动安装Redis,后面会出Reids安装博文,请出门左拐。
    Linux环境配置:Centos 7.4 Redis 版本:4.0.2 
    版本查看命令:redis-server -v 
    
1. 构建 Spring Boot 工程

    选择依赖:devtols,web,lombok,完成工程创建
2. 配置 pom.xml 文件
    添加redis 依赖

<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.62</version>
</dependency>

3. 创建Redis 配置文

package com.test.springredis.controller;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@EnableCaching //开启注解
public class RedisConfig extends CachingConfigurerSupport {

  /**
   * retemplate相关配置
   * @param factory
   * @return
   */
  @Bean
  public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {

    RedisTemplate<String, Object> template = new RedisTemplate<>();
    // 配置连接工厂
    template.setConnectionFactory(factory);

    //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
    Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);

    ObjectMapper om = new ObjectMapper();
    // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
    om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    jacksonSeial.setObjectMapper(om);

    // 值采用json序列化
    template.setValueSerializer(jacksonSeial);
    //使用StringRedisSerializer来序列化和反序列化redis的key值
    template.setKeySerializer(new StringRedisSerializer());

    // 设置hash key 和value序列化模式
    template.setHashKeySerializer(new StringRedisSerializer());
    template.setHashValueSerializer(jacksonSeial);
    template.afterPropertiesSet();

    return template;
  }

  /**
   * 对hash类型的数据操作
   *
   * @param redisTemplate
   * @return
   */
  @Bean
  public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
    return redisTemplate.opsForHash();
  }

  /**
   * 对redis字符串类型数据操作
   *
   * @param redisTemplate
   * @return
   */
  @Bean
  public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
    return redisTemplate.opsForValue();
  }

  /**
   * 对链表类型的数据操作
   *
   * @param redisTemplate
   * @return
   */
  @Bean
  public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
    return redisTemplate.opsForList();
  }

  /**
   * 对无序集合类型的数据操作
   *
   * @param redisTemplate
   * @return
   */
  @Bean
  public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
    return redisTemplate.opsForSet();
  }

  /**
   * 对有序集合类型的数据操作
   *
   * @param redisTemplate
   * @return
   */
  @Bean
  public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
    return redisTemplate.opsForZSet();
  }

}

4. 配置 application.yml 文件

spring:
  redis:
    host: *.*.*.*        #redis ip地址
    port: 6379            #redis 端口
    password: 123        #redis 密码
    jedis:
      pool:
        max-active: 8
        max-wait: -1
        max-idle: 500
        min-idle: 0
    lettuce:
      shutdown-timeout: 0

5. 通过测试用例测试redi

@Autowired
private RedisTemplate<String,String> redisTemplate;

@Test
void contextLoads() {
    redisTemplate.opsForValue().set("myKey","myValue");
    System.out.println(redisTemplate.opsForValue().get("myKey"));
}

6. 通过Restful 接口进行redis操作
    编写Controller 接口类

import com.alibaba.fastjson.JSON;
import com.test.springredis.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Api(description = "用户操作接口asdfasdfa")
@RequestMapping("/redisex")
@RestController
public class RedisControllerEx {

  @Autowired
  private StringRedisTemplate stringRedisTemplate;

  @ApiOperation(value = "获取otp", notes="通过手机号获取OTP验证码")
  @PostMapping("/user")
  public Object addUser(@RequestBody User user){
    stringRedisTemplate.opsForValue().set("user", JSON.toJSONString(user));
    return "success";
  }


  @GetMapping("/user")
  @ApiOperation(value = "获取otp", notes="通过手机号获取OTP验证码")
  public User getUser(){
    return JSON.parseObject(stringRedisTemplate.opsForValue().get("user"), User.class);
  }

  @PostMapping("/addUsers")
  @ApiOperation(value = "获取otp", notes="通过手机号获取OTP验证码")
  public Object addUsers(@RequestBody List<User> users){
    stringRedisTemplate.opsForList().rightPushAll("users", users.stream().map(JSON::toJSONString).collect(Collectors.toList()));
    return "success";
  }

  @GetMapping("/getUsers")
  @ApiOperation(value = "获取otp", notes="通过手机号获取OTP验证码")
  public Object getUsers(){
    List<User> users = new ArrayList<>();
    while (true){
      User user = JSON.parseObject(stringRedisTemplate.opsForList().leftPop("users"), User.class);
      if (Objects.isNull(user)) {
        break;
      }
      users.add(user);
    }
    return users;
  }}

    编写entity 实体类

import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;

@Data
@Accessors(chain = true)
public class User extends JdkSerializationRedisSerializer {

  private Integer id;
  private String name;
}

7. 调用接口测试
    增加用户
    获取用户
    增加用户列表
    获取用户列表
    
8. 最后附上一个 redis公用类

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Freedom3568

技术域不存在英雄主义,不进则退

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

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

打赏作者

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

抵扣说明:

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

余额充值