共計(jì) 7781 個(gè)字符,預(yù)計(jì)需要花費(fèi) 20 分鐘才能閱讀完成。
自動(dòng)寫(xiě)代碼機(jī)器人,免費(fèi)開(kāi)通
這篇文章主要介紹 Redis 框架如何搭建 SpringBoot2.X,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
一、使用 Spring Initializr 創(chuàng)建項(xiàng)目 web 項(xiàng)目
1、File→New→Project
2、點(diǎn)擊 Next 如圖所示,命名好 Group 和 Artifact
3、Next 后如圖所示,勾選中需要的依賴(lài),Spring Initializr 會(huì)自動(dòng)導(dǎo)入所需的 starter
4、創(chuàng)建項(xiàng)目成功后,pom.xml 文件中的依賴(lài)如下
?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ù)庫(kù)數(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(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 + ]
}
注意:
在寫(xiě) JavaBean 對(duì)象時(shí)需要實(shí)現(xiàn) Serializable 接口否則會(huì)報(bào)以下錯(cuò)誤:
Cannot deserialize; nested exception is org.springframework.core.serializer.support.SerializationFailedException
7、整合 Mybatis 操作數(shù)據(jù)庫(kù),在 application.properties 配置文件中配置數(shù)據(jù)源信息
#serverTimezone 用于指定時(shí)區(qū),不然會(huì)報(bào)錯(cuò)
spring.datasource.url=jdbc:mysql://localhost:3306/cache?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
# 開(kāi)啟駝峰命名法規(guī)則
mybatis.configuration.map-underscore-to-camel-case=true
#日志級(jí)別
logging.level.com.henya.springboot.mapper=debug
8、使用注解版 Mybatis 創(chuàng)建 Mapper
package com.henya.springboot.mapper;
@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 所在的接口,只需要加在主程序類(lèi)上即可。除此之外,還要使用 @EnableCaching 用于開(kāi)啟緩存。
@MapperScan(com.henya.springboot.mapper)
@SpringBootApplication
@EnableCaching // 開(kāi)啟緩存
public class SpringBootRedisApplication {public static void main(String[] args) {SpringApplication.run(SpringBootRedisApplication.class, args);
}
9、編寫(xiě) Service 類(lèi),用于訪問(wèn)數(shù)據(jù)庫(kù)或 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( 開(kāi)始查詢(xún) + id + 號(hào)員工
Employee employee = employeeMapper.getEmpById(id);
return employee;
* @CachePut:既調(diào)用方法(這個(gè)方法必須要執(zhí)行),又更新緩存數(shù)據(jù)
* @param employee
* @return
@CachePut(value = emp ,key = #result.id)
public Employee updateEmp(Employee employee){System.err.println( 開(kāi)始更新 + employee.getId() + 號(hào)員工
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、編寫(xiě) Controller 類(lèi)
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;
}
二、測(cè)試 SpringBoot 整合 Redis 是否成功
1、在瀏覽器訪問(wèn),也可以使用測(cè)試類(lèi),筆者使用了瀏覽器訪問(wèn) http://localhost:8080/emp/ 1 進(jìn)行測(cè)試,初次訪問(wèn)時(shí),控制臺(tái)會(huì)提示開(kāi)始查詢(xún) 1 號(hào)員工,如圖所示。
2、再次訪問(wèn)時(shí),控制臺(tái)并沒(méi)有 sql 日志,如圖所示。
3、此時(shí)使用 RedisDesktopManager 工具查看 redis 時(shí)有數(shù)據(jù),并且 cacheName 為 emp,如圖所示
只是 emp 對(duì)象被序列化了。查看源碼可知 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)會(huì)將 CacheName 作為 key 的前綴
return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
}
以上是“Redis 框架如何搭建 SpringBoot2.X”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注丸趣 TV 行業(yè)資訊頻道!
向 AI 問(wèn)一下細(xì)節(jié)
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!