springboot集成redis

2 篇文章 0 订阅

第零步

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

第一步  application.yml 配置文件 配置

spring:

redis:
  database: 0
  host: 172.18.0.88
  port: 6378
  password: 123456
  jedis:
    pool:
      maxActive: 3
      maxIdle: 3
      maxWait: -1
      minIdle: 0
  timeout: 15000

第二步 创建工具类

package com.zzh.elite.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * redis操作工具类.</br>
 * (基于RedisTemplate)
 * @author zzh
 * 20191217
 */
@Component
public class RedisUtils {
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 写入缓存
     * */
    public boolean set(final String key,String value){
        boolean result=false;
       try{
           redisTemplate.opsForValue().set(key,value);
           result=true;
       }catch (Exception e){
            e.printStackTrace();
       }
        return result;
    }
    /**
     * 读取缓存
     * */
    public String get(final String key){
        return (String) redisTemplate.opsForValue().get(key);
    }
    /**
     * 更新缓存
     * */
    public boolean getAndSet(final String key,String value){
        boolean result=false;
        try{
            redisTemplate.opsForValue().getAndSet(key,value);
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 删除缓存
     * */
    public boolean delete(final String key){
        boolean result=false;
        try {
            redisTemplate.delete(key);
            result=true;
        }catch (Exception e){
            e.printStackTrace();
        }
            return result;
    }
}

第三步 测试

package com.zzh.elite.dto;

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

@Data
public class RedisTestDTO {
    @ApiModelProperty(value="缓存key")
    private String redisKey;
    @ApiModelProperty(value="缓存value")
    private String redisValue;
}
@Autowired
RedisUtils redisUtils;
@RequestMapping(value = "test/redis",method = RequestMethod.POST)
@ApiOperation("redis测试")
public ResponseMessage<RedisTestVO> redis(@RequestBody RedisTestDTO redisTestDTO){
    redisUtils.set(redisTestDTO.getRedisKey(),redisTestDTO.getRedisValue());
    RedisTestVO redisTestVO=new RedisTestVO();
    redisTestVO.setRedisKey(redisTestDTO.getRedisKey());
    redisTestVO.setRedisValue(redisUtils.get(redisTestDTO.getRedisKey()));
    return CommonUtils.okResponseVO(redisTestVO);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值