SpringBoot Redis的简单集成

本文详细介绍了如何在Spring Boot项目中集成Redis,包括依赖配置、属性设置、服务封装及Swagger API测试,为开发者提供了一个完整的实践指南。

1、redis的安装和简单的命令可以参考的其他文章Redis 采用指令Redis window上安装和使用

2、pom的依赖。

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

3、application.properties的配置。

server:
  port: 9001

spring:
  profiles:
    active: dev

  redis:
    database: 1
    host: 127.0.0.1        #119.23.206.197  127.0.0.1
    port: 6379             #6379            6379
    password: zhuoxiaojie     #19960815        zhuoxiaojie
    pool:
      max-active: 1000   #最大连接数
      max-wait: 2000      #阻塞时间
      max-idle: 100      #最大空闲
      min-idle: 20       #最小空闲
    timeout: 5000

4、对redis服务的简单封装,具有快速使用增删改查。

package com.zxj.reptile.service.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisService {
    // Redis为我们提供了两个模板
    // StringRedisTemplate主要提供给我们操作字符串;
    // RedisTemplate提供给我们操作对象;操作对象的时候最好自定义序列化器

    @Autowired
    private StringRedisTemplate template;

    public boolean remove(String key) {
        if (template.hasKey(key)) {
            return template.delete(key);
        }
        return false;
    }

    public String get(String key) {
        if (template.hasKey(key)) {
            ValueOperations<String, String> operations = template.opsForValue();
            return operations.get(key);
        }
        return null;
    }

    public boolean set(String key, String value) {
        try {
            if (template != null) {
                ValueOperations<String, String> operations = template.opsForValue();
                operations.set(key, value);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean set(String key, String value, Long expireTime, TimeUnit timeUnit) {
        try {
            if (template != null) {
                ValueOperations<String, String> operations = template.opsForValue();
                operations.set(key, value);
                template.expire(key, expireTime, timeUnit);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}

5、swagger的api测试代码。

package com.zxj.reptile.api.demo;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zxj.reptile.api.AjaxJson;
import com.zxj.reptile.module.demo.entity.Demo;
import com.zxj.reptile.module.demo.service.IDemoService;
import com.zxj.reptile.service.redis.RedisService;
import com.zxj.reptile.utils.PropertyUtils;
import com.zxj.reptile.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Api(value = "demo", tags = "demo测试Api")
@RestController
@RequestMapping("demo")
public class DemoApi {
    @Autowired
    private RedisService redisService;

    @ApiOperation(value = "测试Redis", notes = "测试Redis")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "key", value = "key", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "value", value = "value", dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "testRedis", method = RequestMethod.GET)
    public AjaxJson testRedis(@RequestParam(value = "key") String key, @RequestParam(value = "value") String value) {
        AjaxJson ajaxJson = new AjaxJson<>();
        try {
            if (redisService.set(key, value)) {
                ajaxJson.success("返回redis的值");
                ajaxJson.setData(redisService.get(key));
            } else {
                ajaxJson.error("失败:");
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.error("失败: " + e.getMessage());
        }
        return ajaxJson;
    }
}

6、记得测试前,要将本地的redis服务打开,测试结果。

 

SpringBoot是当前比较流行的Java开发框架之一,而Redis则是非常流行的高性能的key-value存储系统。在实际开发中,需要使用 Redis来进行缓存、Session等功能的实现,并且也需要在SpringBoot项目中集成Redis。下面介绍下SpringBoot集成Redis的样例。 1.添加Redis依赖 在pom.xml文件中添加Redis依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2.配置连接Redis 在application.properties文件中设置Redis的相关连接信息,如下: ``` # Redis服务器地址 spring.redis.host=127.0.0.1 # Redis服务器连接端口 spring.redis.port=6379 # Redis服务器连接密码(默认为空) spring.redis.password= ``` 3.使用RedisTemplate操作Redis 通过SpringBootRedisTemplate可以方便地操作Redis,如下: ``` @Autowired private RedisTemplate<String, Object> redisTemplate; public void setValue(String key, Object value) { redisTemplate.opsForValue().set(key, value); } public Object getValue(String key) { return redisTemplate.opsForValue().get(key); } public void delValue(String key) { redisTemplate.delete(key); } ``` 上述代码中使用了RedisTemplate的opsForValue()方法来进行Redis的操作,其中setValue方法可以向Redis中缓存数据,getValue方法可以从Redis中获取数据,而delValue方法可以删除Redis中存储的数据。 以上就是SpringBoot集成Redis的样例,通过使用SpringBootRedisTemplate以及设置application.properties文件中的相关配置信息来实现Redis的缓存功能,在实际开发中可以根据具体业务进行相应的扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值