欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

从零搭建SpringBoot2.X整合Redis框架的详细教程

程序员文章站 2022-03-10 15:25:07
最近也不知道写啥,看之前写过kafka整合springboot的文章,大家反响还挺热烈的,嘿嘿嘿,就感觉帮助到大家了还挺好的,也算是达到了自己的目的,正好,今天业务模块是springboot整合red...

最近也不知道写啥,看之前写过kafka整合springboot的文章,大家反响还挺热烈的,嘿嘿嘿,就感觉帮助到大家了还挺好的,也算是达到了自己的目的,正好,今天业务模块是springboot整合redis,因为之前做过,所以有现成的代码,cv一下之后就可以了,所以时间比较多,那就给大家整理一下springboot整合redis的代码实现吧,从项目搭建到源码实现,下面全都有,耐心看完,相信会对你有所帮助的

好了,话不多说,我们开始吧,同样的,还是建议能够自己在自己的pc端实现一下
个人公众号:java架构师联盟,每日更新技术好文

一、使用spring initializr创建项目web项目

1、file→new→project

从零搭建SpringBoot2.X整合Redis框架的详细教程

2、点击next如图所示,命名好group和artifact

从零搭建SpringBoot2.X整合Redis框架的详细教程

3、next后如图所示,勾选中需要的依赖,spring initializr会自动导入所需的starter

从零搭建SpringBoot2.X整合Redis框架的详细教程

4、创建项目成功后,pom.xml文件中的依赖如下

<?xml version="1.0" encoding="utf-8"?>
<project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
	xsi:schemalocation="http://maven.apache.org/pom/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelversion>4.0.0</modelversion>
	<parent>
		<groupid>org.springframework.boot</groupid>
		<artifactid>spring-boot-starter-parent</artifactid>
		<version>2.2.2.release</version>
		<relativepath/> <!-- lookup parent from repository -->
	</parent>
	<groupid>com.heny</groupid>
	<artifactid>spring-boot-redis</artifactid>
	<version>0.0.1-snapshot</version>
	<name>spring-boot-redis</name>
	<description>demo project for spring boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupid>org.springframework.boot</groupid>
			<artifactid>spring-boot-starter-web</artifactid>
		</dependency>
		<dependency>
			<groupid>org.mybatis.spring.boot</groupid>
			<artifactid>mybatis-spring-boot-starter</artifactid>
			<version>2.1.1</version>
		</dependency>

		<dependency>
			<groupid>mysql</groupid>
			<artifactid>mysql-connector-java</artifactid>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupid>org.springframework.boot</groupid>
			<artifactid>spring-boot-starter-test</artifactid>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupid>org.junit.vintage</groupid>
					<artifactid>junit-vintage-engine</artifactid>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupid>org.springframework.boot</groupid>
				<artifactid>spring-boot-maven-plugin</artifactid>
			</plugin>
		</plugins>
	</build>

</project>

5、在pom.xml文件中添加redis的starter

<dependency>
		<groupid>org.springframework.boot</groupid>
		<artifactid>spring-boot-starter-data-redis</artifactid>
	</dependency>

6、创建javabean用于封装数据库数据,需要实现serializable

package com.henya.springboot.bean;

import java.io.serializable;

public class employee implements serializable{
	
	private integer id;
	private string lastname;
	private string email;
	private integer gender; //性别 1男 0女
	private integer did;
	
	
	public employee() {
		super();
	}

	
	public employee(integer id, string lastname, string email, integer gender, integer did) {
		super();
		this.id = id;
		this.lastname = lastname;
		this.email = email;
		this.gender = gender;
		this.did = did;
	}
	
	public integer getid() {
		return id;
	}
	public void setid(integer id) {
		this.id = id;
	}
	public string getlastname() {
		return lastname;
	}
	public void setlastname(string lastname) {
		this.lastname = lastname;
	}
	public string getemail() {
		return email;
	}
	public void setemail(string email) {
		this.email = email;
	}
	public integer getgender() {
		return gender;
	}
	public void setgender(integer gender) {
		this.gender = gender;
	}
	public integer getdid() {
		return did;
	}
	public void setdid(integer did) {
		this.did = did;
	}
	@override
	public string tostring() {
		return "employee [id=" + id + ", lastname=" + lastname + ", email=" + email + ", gender=" + gender + ", did="
				+ did + "]";
	}
}

注意:
在写javabean对象时需要实现serializable接口否则会报以下错误:

cannot deserialize; nested exception is org.springframework.core.serializer.support.serializationfailedexception

7、整合mybatis操作数据库,在application.properties配置文件中配置数据源信息

#servertimezone用于指定时区,不然会报错
spring.datasource.url=jdbc:mysql://localhost:3306/cache?servertimezone=utc
spring.datasource.username=root
spring.datasource.password=123456

# 开启驼峰命名法规则
mybatis.configuration.map-underscore-to-camel-case=true
#日志级别
logging.level.com.henya.springboot.mapper=debug

8、使用注解版mybatis创建mapper

package com.henya.springboot.mapper;


import com.henya.springboot.bean.employee;
import org.apache.ibatis.annotations.*;

@mapper
public interface employeemapper {

 @select("select * from employee where id=#{id}")
 public employee getempbyid(integer id);

 @update("update employee set lastname=#{lastname},email=#{email},gender=#{gender},d_id=#{did} where id=#{id}")
 public void updateemp(employee employee);

 @delete("delete from emlpoyee where id=#{id}")
 public void delempbyid(integer id);

 @insert("insert into employee(lastname, email, gender, d_id) values (#{lastname}, #{email}, #{gender}, #{did})")
 public employee insertemp(employee employee);

 @select("select * from employee where lastname=#{lastname}")
 public employee getempbylastname(string lastname);
}

注意:
需要使用使用@mapperscan注解扫描mapper所在的接口,只需要加在主程序类上即可。除此之外,还要使用@enablecaching用于开启缓存。

@mapperscan("com.henya.springboot.mapper")
@springbootapplication
@enablecaching //开启缓存
public class springbootredisapplication {

	public static void main(string[] args) {
		springapplication.run(springbootredisapplication.class, args);
	}
}

9、编写service类,用于访问数据库或redis缓存

package com.henya.springboot.service;
import com.henya.springboot.bean.employee;
import com.henya.springboot.mapper.employeemapper;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.cache.annotation.*;
import org.springframework.stereotype.service;

@cacheconfig(cachenames = "emp") //抽取缓存的公共配置
@service
public class employeeservice {
 @autowired
 employeemapper employeemapper;

 /**
 * @param id
 * @return
 */
 @cacheable(cachenames = {"emp"},keygenerator = "mykeygenerator")
 public employee getempbyid(integer id) {
 system.err.println("开始查询"+ id +"号员工");
 employee employee = employeemapper.getempbyid(id);
 return employee;
 }

 /**
 * @cacheput:既调用方法(这个方法必须要执行),又更新缓存数据
 * @param employee
 * @return
 */
 @cacheput(value = "emp",key = "#result.id")
 public employee updateemp(employee employee){
 system.err.println("开始更新" + employee.getid() + "号员工");
 employeemapper.updateemp(employee);
 return employee;
 }

 /**
 * @cacheevict:缓存清除
 * @param id
 */
 @cacheevict(value = "emp",beforeinvocation = true)
 public void deleteemp(integer id){
 system.err.println("删除" + id + "员工");
 int i = 10/0;
 }

10、编写controller类

package com.henya.springboot.controller;


import com.henya.springboot.bean.employee;
import com.henya.springboot.service.employeeservice;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.pathvariable;
import org.springframework.web.bind.annotation.restcontroller;

/**
 * @description:
 * @author:henya
 * @creattime:2019/12/1 12:44
 */
@restcontroller
public class employeecontroller {
 @autowired
 employeeservice employeeservice;

 @getmapping("/emp/{id}")
 public employee getempbyid(@pathvariable("id") integer id){
 employee employee = employeeservice.getempbyid(id);
 return employee;
 }

 @getmapping("/emp")
 public employee updateemp(employee employee){
 employee emp = employeeservice.updateemp(employee);
 return emp;
 }
}

二、测试springboot整合redis是否成功

1、在浏览器访问,也可以使用测试类,笔者使用了浏览器访问http://localhost:8080/emp/1进行测试,初次访问时,控制台会提示开始查询1号员工,如图所示。

从零搭建SpringBoot2.X整合Redis框架的详细教程

2、再次访问时,控制台并没有sql日志,如图所示。

从零搭建SpringBoot2.X整合Redis框架的详细教程

3、此时使用redisdesktopmanager工具查看redis时有数据,并且cachename为emp,如图所示

从零搭建SpringBoot2.X整合Redis框架的详细教程

只是emp对象被序列化了。查看源码可知redis默认使用jdk进行序列化。

static redisserializer<object> java(@nullable classloader classloader) {
 return new jdkserializationredisserializer(classloader);
 }

查看redisserializer接口的实现有以下几种:

从零搭建SpringBoot2.X整合Redis框架的详细教程

我们常用的就是以json的格式进行序列化。但是需要自定义rediscachemanager。

三、自定义rediscachemanager

package com.henya.springboot.config;
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.cache.rediscachewriter;
import org.springframework.data.redis.connection.redisconnectionfactory;
import org.springframework.data.redis.serializer.genericjackson2jsonredisserializer;
import org.springframework.data.redis.serializer.redisserializationcontext;
import org.springframework.data.redis.serializer.redisserializer;

/**
 * @description:
 * @author:henya
 * @creattime:2019/12/6 20:50
 */
@configuration
public class myredisconfig {
 @bean
 public rediscachemanager empcachemanager(redisconnectionfactory redisconnectionfactory){
 //rediscachemanager rediscachemanager = new rediscachemanager(redisconnectionfactory);
 rediscachewriter rediscachewriter = rediscachewriter.nonlockingrediscachewriter(redisconnectionfactory);

 redisserializer<object> redisserializer = new genericjackson2jsonredisserializer();

 redisserializationcontext.serializationpair<object> pair = redisserializationcontext.serializationpair.fromserializer(redisserializer);
 rediscacheconfiguration rediscacheconfiguration = rediscacheconfiguration.defaultcacheconfig().serializevalueswith(pair);
 // 默认会将cachename作为key的前缀
 return new rediscachemanager(rediscachewriter, rediscacheconfiguration);
 }
 }

此时,redis中缓存数据就以json的格式进行序列化,如图所示。

从零搭建SpringBoot2.X整合Redis框架的详细教程

到此这篇关于从零搭建springboot2.x整合redis框架的详细教程的文章就介绍到这了,更多相关springboot2.x整合redis框架内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: SpringBoot2.X Redis