最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

從零搭建SpringBoot2.X整合Redis框架的詳細(xì)教程

 更新時間:2020年12月08日 15:21:03   作者:Java愛coding  
這篇文章主要介紹了從零搭建SpringBoot2.X整合Redis框架的詳細(xì)教程,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

最近也不知道寫啥,看之前寫過Kafka整合Springboot的文章,大家反響還挺熱烈的,嘿嘿嘿,就感覺幫助到大家了還挺好的,也算是達(dá)到了自己的目的,正好,今天業(yè)務(wù)模塊是springboot整合redis,因?yàn)橹白鲞^,所以有現(xiàn)成的代碼,cv一下之后就可以了,所以時間比較多,那就給大家整理一下Springboot整合Redis的代碼實(shí)現(xiàn)吧,從項(xiàng)目搭建到源碼實(shí)現(xiàn),下面全都有,耐心看完,相信會對你有所幫助的

好了,話不多說,我們開始吧,同樣的,還是建議能夠自己在自己的PC端實(shí)現(xiàn)一下
個人公眾號:Java架構(gòu)師聯(lián)盟,每日更新技術(shù)好文

一、使用Spring Initializr創(chuàng)建項(xiàng)目web項(xiàng)目

1、File→New→Project

2、點(diǎn)擊Next如圖所示,命名好Group和Artifact

3、Next后如圖所示,勾選中需要的依賴,Spring Initializr會自動導(dǎo)入所需的starter

4、創(chuàng)建項(xiàng)目成功后,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、創(chuàng)建JavaBean用于封裝數(shù)據(jù)庫數(shù)據(jù),需要實(shí)現(xiàn)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對象時需要實(shí)現(xiàn)Serializable接口否則會報以下錯誤:

Cannot deserialize; nested exception is org.springframework.core.serializer.support.SerializationFailedException

7、整合Mybatis操作數(shù)據(jù)庫,在application.properties配置文件中配置數(shù)據(jù)源信息

#serverTimezone用于指定時區(qū),不然會報錯
spring.datasource.url=jdbc:mysql://localhost:3306/cache?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456

# 開啟駝峰命名法規(guī)則
mybatis.configuration.map-underscore-to-camel-case=true
#日志級別
logging.level.com.henya.springboot.mapper=debug

8、使用注解版Mybatis創(chuàng)建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類,用于訪問數(shù)據(jù)庫或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:既調(diào)用方法(這個方法必須要執(zhí)行),又更新緩存數(shù)據(jù)
 * @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進(jìn)行測試,初次訪問時,控制臺會提示開始查詢1號員工,如圖所示。

2、再次訪問時,控制臺并沒有sql日志,如圖所示。

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

只是emp對象被序列化了。查看源碼可知Redis默認(rèn)使用Jdk進(jìn)行序列化。

static RedisSerializer<Object> java(@Nullable ClassLoader classLoader) {
 return new JdkSerializationRedisSerializer(classLoader);
 }

查看RedisSerializer接口的實(shí)現(xiàn)有以下幾種:

我們常用的就是以json的格式進(jìn)行序列化。但是需要自定義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);
 // 默認(rèn)會將CacheName作為key的前綴
 return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
 }
 }

此時,Redis中緩存數(shù)據(jù)就以Json的格式進(jìn)行序列化,如圖所示。

到此這篇關(guān)于從零搭建SpringBoot2.X整合Redis框架的詳細(xì)教程的文章就介紹到這了,更多相關(guān)SpringBoot2.X整合Redis框架內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • redis replication環(huán)形緩沖區(qū)算法詳解

    redis replication環(huán)形緩沖區(qū)算法詳解

    這篇文章主要介紹了redis replication環(huán)形緩沖區(qū)算法的使用,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2025-04-04
  • 基于Redis分布式BitMap的應(yīng)用分析

    基于Redis分布式BitMap的應(yīng)用分析

    這篇文章主要介紹了基于Redis分布式BitMap的應(yīng)用,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-03-03
  • 壓縮Redis里的字符串大對象操作

    壓縮Redis里的字符串大對象操作

    這篇文章主要介紹了壓縮Redis里的字符串大對象操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • 一文詳解如何停止/重啟/啟動Redis服務(wù)

    一文詳解如何停止/重啟/啟動Redis服務(wù)

    Redis是當(dāng)前比較熱門的NOSQL系統(tǒng)之一,它是一個key-value存儲系統(tǒng),這篇文章主要給大家介紹了關(guān)于如何停止/重啟/啟動Redis服務(wù)的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2024-03-03
  • redis 億級數(shù)據(jù)讀取的實(shí)現(xiàn)

    redis 億級數(shù)據(jù)讀取的實(shí)現(xiàn)

    本文主要介紹了redis 億級數(shù)據(jù)讀取的實(shí)現(xiàn),億級數(shù)據(jù)規(guī)模下實(shí)現(xiàn)高效的數(shù)據(jù)讀取成為了許多企業(yè)和開發(fā)者面臨的重大挑戰(zhàn),下面就來介紹一下,感興趣的可以了解一下
    2024-08-08
  • Redis教程(七):Key操作命令詳解

    Redis教程(七):Key操作命令詳解

    這篇文章主要介紹了Redis教程(七):Key操作命令詳解,本文講解了Key操作命令概述、相關(guān)命令列表、命令使用示例等內(nèi)容,需要的朋友可以參考下
    2015-04-04
  • macOS上Redis的安裝與測試操作

    macOS上Redis的安裝與測試操作

    這篇文章主要介紹了macOS上Redis的安裝與測試操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-07-07
  • 為啥Redis使用pipelining會更快

    為啥Redis使用pipelining會更快

    這篇文章主要介紹了為啥Redis使用pipelining會更快,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11
  • 使用redis獲取自增序列號實(shí)現(xiàn)方式

    使用redis獲取自增序列號實(shí)現(xiàn)方式

    這篇文章主要介紹了使用redis獲取自增序列號實(shí)現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-12-12
  • Spring?redis使用報錯Read?timed?out排查及解決過程

    Spring?redis使用報錯Read?timed?out排查及解決過程

    項(xiàng)目使用spring集成redis,偶爾會出現(xiàn)read timed out的情況,剛開始以為是網(wǎng)絡(luò)不穩(wěn)定引起的,后面發(fā)現(xiàn)影響業(yè)務(wù)測試的準(zhǔn)確性,這篇文章主要給大家介紹了關(guān)于Spring redis使用報錯Read timed out排查及解決過程的相關(guān)資料,需要的朋友可以參考下
    2024-02-02

最新評論

盐山县| 武川县| 无锡市| 株洲县| 姚安县| 泰顺县| 辽中县| 弥勒县| 通化县| 沿河| 禄劝| 固镇县| 元朗区| 保定市| 黄陵县| 桦南县| 金阳县| 军事| 浦东新区| 习水县| 安乡县| 盐津县| 新兴县| 石屏县| 金堂县| 贞丰县| 邻水| 正宁县| 安多县| 叶城县| 麟游县| 兰州市| 永平县| 奈曼旗| 静海县| 禹城市| 勃利县| 芦溪县| 手游| 彰化市| 利川市|