Spring Boot整合Redis(gradle + gson + lombok + redisTemplate)

news2025/2/22 13:39:00

本文创建了gradle项目,用来整合Spring Boot和Redis,用到了gradle + gson + lombok + redisTemplate等技术。
重要文件:

文件名说明
build.gradlegradle配置文件
Redis2Application.java启动类
Controller.java控制器类
StudentService.java业务逻辑类
StudentDao.javaDAO类,用于和Redis直接交互
Student.java模型类,用于映射数据和Java对象
application.java配置文件

初始化

在https://start.spring.io/初始化:

1

引入依赖

在build.gradle里引入依赖:

plugins {
	id 'java'
	id 'org.springframework.boot' version '2.7.8-SNAPSHOT'
	id 'io.spring.dependency-management' version '1.0.15.RELEASE'
}

group = 'com.xiaolong'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

configurations {
	compileOnly {
		extendsFrom annotationProcessor
	}
}

repositories {
	mavenCentral()
	maven { url 'https://repo.spring.io/milestone' }
	maven { url 'https://repo.spring.io/snapshot' }
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-data-redis'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	implementation 'com.google.code.gson:gson:2.10'
	compileOnly 'org.projectlombok:lombok'
	annotationProcessor 'org.projectlombok:lombok'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

tasks.named('test') {
	useJUnitPlatform()
}

配置文件和启动类

在resources目录下的application.yml文件中配置Redis数据库连接,本地的6379端口:

spring:
  redis:
    host:localhost
    port:6078

如果原来有其他配置文件,可以删掉,新建application.yml。

启动类,这里用注解SpringBootApplication的exclude排除了数据库的驱动程序,免去再去安装数据库驱动,Redis不需要数据库驱动类Redis2Application:

package com.xiaolong.redis2;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class Redis2Application {

	public static void main(String[] args) {
		SpringApplication.run(Redis2Application.class, args);
	}

}

控制类和业务模型类

对外提供接口服务的Controller.java

package com.xiaolong.redis2.controller;

import com.xiaolong.redis2.model.Student;
import com.xiaolong.redis2.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Controller {
    @Autowired
    StudentService studentService;
    @RequestMapping("/saveStudent")
    public void saveStudent(){
        Student newStudent = new Student();
        newStudent.setId("student_001");
        newStudent.setName("Peter");
        newStudent.setScore("100");
        studentService.saveStudent(newStudent);
    }
    @RequestMapping("/findByID/{id}")
    public Student findByID(@PathVariable String id){
        return studentService.findByID(id);
    }
    @RequestMapping("/deleteByID/{id}")
    public void deleteByID(@PathVariable String id){
        studentService.deleteByID(id);
    }
}

这里用注解@RestController注解设置控制器类,用注解@Autowired依赖注入业务逻辑类,用注解@RequestMapping映射路由。

业务模型类:

package com.xiaolong.redis2.model;

import lombok.Data;
@Data
public class Student {
    private String id;
    private String name;
    private String score;
}

这里用到了lombok的注解@Data,无需再去写get和set方法。

业务逻辑类

package com.xiaolong.redis2.service;

import com.xiaolong.redis2.StudentDao;
import com.xiaolong.redis2.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StudentService {
    @Autowired
    private StudentDao studentDao;
    public void saveStudent(Student student) {
        studentDao.saveStudent(student.getId(), 3600, student);
    }
    public Student findByID(String id){
        return studentDao.findByID(id);
    }
    public void deleteByID(String id){
        studentDao.deleteByID(id);
    }
}

通过注解@Service设置业务类,注解@Autowired自动注入DAO对象。

Redis DAO数据库交互类

package com.xiaolong.redis2;

import com.google.gson.Gson;
import com.xiaolong.redis2.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.concurrent.TimeUnit;

@Repository
public class StudentDao {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    public void saveStudent(String id, int expireTime, Student student) {
        Gson gson = new Gson();
        redisTemplate.opsForValue().set(id, gson.toJson(student), expireTime, TimeUnit.SECONDS);
    }

    public Student findByID(String id) {
        Gson gson = new Gson();
        Student student = null;
        String studentJson = redisTemplate.opsForValue().get(id);
        if(studentJson != null && !studentJson.equals("")) {
            student = gson.fromJson(studentJson, Student.class);
        }
        return student;
    }

    public void deleteByID(String id) {
        redisTemplate.opsForValue().getOperations().delete(id);
    }
}

这里使用redisTemplate与Redis交互,用GSON把数据对象保存成json格式。

结果

http://127.0.0.1:8080/saveStudent新建数据:
1
查询:
1

删除数据:
1

1

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/163388.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

深入解析Linux虚拟化KVM-Qemu分析之virtio设备

说明&#xff1a; KVM版本&#xff1a;5.9.1QEMU版本&#xff1a;5.0.0工具&#xff1a;Source Insight 3.5&#xff0c; Visio 1. 概述 先来张图&#xff1a; 图中罗列了四个关键模块&#xff1a;Virtio Device、Virtio Driver、Virtqueue、Notification&#xff08;eventfd…

Linux——简单了解文件与目录结构

1、 Linux 文件 1.1 概述 Linux系统 一切皆文件。 从我们刚接触到Linux系统&#xff0c;就能听到这句话&#xff1a;Linux系统 一切皆文件。 我们来看看Linux文件系统和Windos的差异&#xff1a; Windows &#xff0c;我们知道一台新的电脑到手之后&#xff0c;往往都只有一…

Vue2的双向绑定真的就是观察者模式吗?

导语建议先看看往期的推文&#xff0c;对vue响应式有一定理解后再阅读本文。Vue的双向绑定&#xff08;数据劫持&#xff09;响应式与观察者模式&#xff08;特别是附录&#xff0c;观察者模式与发布订阅模式&#xff09;关于Vue2深入响应式原理&#xff0c;作者原话为&#xf…

搭建nacos环境(保姆级教程)

2.2.1 服务发现中心 根据上节讲解的网关的架构图&#xff0c;要使用网关首先搭建Nacos。 首先搭建Nacos服务发现中心。 在搭建Nacos服务发现中心之前需要搞清楚两个概念&#xff1a;namespace和group namespace&#xff1a;用于区分环境、比如&#xff1a;开发环境、测试环…

【Linux】进程间管道通信、线程池

目录 一、进程间通信的概念 二、匿名管道 2.1 什么是管道 2.2 管道的实现 2.3 管道的使用 三、进程池 3.1 进程池实现逻辑 3.2 模拟任务表 3.3 进程池的创建 四、命名管道 4.1 创建命名管道 4.2 命令管道的使用 一、进程间通信的概念 进程具有独立性&#xff0c;…

面试系列:单点登录的知识(一)

大家好&#xff0c;我是车辙&#xff0c;由于目前接手的业务涉及到了单点登录&#xff0c;所以一直在疯狂的去补充这方面的知识。也写下了这篇面试形式的文章&#xff0c;写的不好大家轻点 Diss。 面试开始 在焦急的等待中&#xff0c;一位看上去比较年轻的小伙子走了过来。我…

Leetcode:701. 二叉搜索树中的插入操作(C++)

目录 问题描述&#xff1a; 实现代码与解析&#xff1a; 递归&#xff1a; 原理思路&#xff1a; 迭代&#xff1a; 原理思路&#xff1a; 问题描述&#xff1a; 给定二叉搜索树&#xff08;BST&#xff09;的根节点 root 和要插入树中的值 value &#xff0c;将值插入二…

Codeforces Round #843 (Div. 2)——A,B,C,E

​​​​​​​​​​​Dashboard - Codeforces Round #842 (Div. 2) - Codeforces A: 思维构造 题意&#xff1a;给定一个由 ab 组成的字符串&#xff0c;将该字符串拆分成 3 个部分&#xff08;a&#xff0c;b&#xff0c;c&#xff09;&#xff0c;要求中间部分的字典序最大…

2022 年终总结

在 12 月 31 号晚上这天&#xff0c;打开朋友圈大家都在告别 2022、迎接 2023&#xff0c;我却想不到任何值得发的内容。没有外出体会元旦的节日氛围&#xff0c;也没有观看任何跨年活动&#xff0c;2022 年最后一秒跟全年的 3153.6 万秒没有任何区别。 甚至这篇总结都差点没有…

RK3568源码编译与交叉编译环境搭建

本篇进行飞凌OK3568-C开发板的Linux系统开发需要用的软件交叉编译环境的配置。 对于软件开发&#xff0c;如果只是使用C/C代码&#xff0c;则在自己的Ubuntu虚拟机中添加RK3568对应的交叉编译器(gcc/g)即可&#xff0c;如果要进行Qt开发&#xff0c;则还要再交叉编译与RK3568配…

UDS诊断系列介绍09-1485服务

本文框架1. 系列介绍1.1 14服务概述1.2 85服务概述2. 14服务请求与应答2.1 14服务请求2.2 14服务正响应3. 85服务请求与应答3.1 85服务请求3.2 85服务正响应3.3 否定应答4. Autosar系列文章快速链接1. 系列介绍 UDS&#xff08;Unified Diagnostic Services&#xff09;协议&a…

graalvm+spring-cloud-gateway打造又快又小的类nginx本地网关

前言 网关是微服务架构的入口&#xff0c;外网请求通过网关转发到独立的微服务。项目一般会经过多个环境的测试&#xff0c;最终发布到生产。一个http请求&#xff0c;如&#xff1a;http://public_host/api/v1/some_service/some_path?ab&cd会先经过公网域名&#xff0c…

ThinkPHP5.x未开启强制路由(s参数)RCE

官方公告&#xff1a;https://blog.thinkphp.cn/869075 由于框架对控制器名没有进行足够的检测会导致在没有开启强制路由的情况下可能的getshell漏洞&#xff0c;受影响的版本包括5.0和5.1版本 ThinkPHP5基础 环境搭建 官网直接下载完整包 https://www.thinkphp.cn/down/870.…

ElasticSearch集群架构及底层原理

前言ElasticSearch考虑到大数据量的情况&#xff0c;集群有很多的部署模式&#xff0c;本篇不会具体进行演示了&#xff0c;只是说明一下有哪些架构可以选&#xff0c;及一些原理的简单介绍&#xff0c;如果要看具体操作的那么可以自行进行搜索&#xff0c;这不是本篇博客要介绍…

OCR文字识别软件哪个好?7大文字识别软件

由于从各种文档中提取文本的需求非常普遍&#xff0c;许多办公软件或公司都提供了OCR工具。在本文中&#xff0c;我们为您推出了一系列功能强大且易于使用的最佳 OCR 软件。 什么是 OCR 软件&#xff1f; OCR 软件是一种程序或工具&#xff0c;可以使用光学字符识别技术识别数…

小红书数据分析网站:揭晓普通博主1个月涨粉百万的密码!

导语&#xff1a; 随着2023年的来临&#xff0c;回首小红书动态&#xff0c;行业热度依旧高涨&#xff0c;越来越多的达人涌入小红书。在时尚领域&#xff0c;更是出现了如氧化菊这样的大势变装博主&#xff01;短短一周涨粉13W的变装博主为何能突围&#xff0c;强势吸睛呢&am…

[LCTF]bestphp2022安洵杯 babyphp

目录 <1> [LCTF]bestphp‘s revenge SoapClient触发反序列化导致ssrf serialize_hander处理session方式不同导致session注入 crlf漏洞 <2> 安洵杯 babyphp SoapClient 触发ssrf session反序列化 利用文件操作原生类读取flag <3> XCTF Final Web1 解…

Spring Security 解析(六) —— 基于JWT的单点登陆(SSO)开发及原理解析

Spring Security 解析(六) —— 基于JWT的单点登陆(SSO)开发及原理解析 在学习Spring Cloud 时&#xff0c;遇到了授权服务oauth 相关内容时&#xff0c;总是一知半解&#xff0c;因此决定先把Spring Security 、Spring Security Oauth2 等权限、认证相关的内容、原理及设计学习…

[极客大挑战 2019]Secret File

目录 信息收集 解题思路 信息收集 先看源码&#xff0c;发现一个php文件 <a id"master" href"./Archive_room.php" style"background-color:#000000;height:70px;width:200px;color:black;left:44%;cursor:default;">Oh! You found me&…

9.2 容器库概览

文章目录所有容器的共性&#xff1a;迭代器迭代器的范围容器类型成员begin和end成员容器的定义和初始化与顺序容器大小相关的构造函数赋值和swapassignedswap容器大小操作关系运算符所有容器的共性&#xff1a; 表格一&#xff1a; 类型别名说明iterator迭代器const_iterator…