首頁 > 資料庫 > Redis > 主體

整合Redis框架搭建SpringBoot2.X的詳細教學

coldplay.xixi
發布: 2020-12-08 17:46:43
轉載
3080 人瀏覽過

redis資料庫教學欄位介紹從零搭建SpringBoot2.X教學

整合Redis框架搭建SpringBoot2.X的詳細教學

#推薦(免費):


#redis資料庫教學

最近也不知道寫啥,看之前寫過Kafka整合Springboot的文章,大家反應還挺熱烈的,嘿嘿嘿,就感覺幫助到大家了還挺好的,也算是達到了自己的目的,正好,今天業務模組是springboot整合redis,因為之前做過,所以有現成的代碼,cv一下之後就可以了,所以時間比較多,那就給大家整理一下Springboot整合Redis的程式碼實現吧,從專案搭建到原始碼實現,下面全都有,耐心看完,相信會對你有所幫助的

好了,話不多說,我們開始吧,同樣的,還是建議能夠自己在自己的PC端實現一下

個人公眾號:Java架構師聯盟,每日更新技術好文

一、使用Spring Initializr創建專案web專案

1、File→New→Project


2、點選Next如圖所示,命名好Group和Artifact


3、Next後如圖所示,勾選所需的依賴,Spring Initializr會自動匯入所需的starter


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號員工,如圖所示。


2、再次造訪時,控制台並沒有sql日誌,如圖所示。

3、此時使用RedisDesktopManager工具查看redis時有數據,且cacheName為emp,如圖所示

只是emp物件被序列化了。查看原始碼可知Redis預設使用Jdk進行序列化。

static RedisSerializer<Object> java(@Nullable ClassLoader classLoader) {
 return new JdkSerializationRedisSerializer(classLoader);
 }
登入後複製
###查看RedisSerializer介面的實作有以下幾種:###############我們常用的就是以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的格式進行序列化,如圖所示。 ###

以上是整合Redis框架搭建SpringBoot2.X的詳細教學的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:jb51.net
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!