Spring Boot整合Spring Cache及Redis過程解析
這篇文章主要介紹了Spring Boot整合Spring Cache及Redis過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
1.安裝redis
a.由于官方是沒有Windows版的,所以我們需要下載微軟開發(fā)的redis,網(wǎng)址:
https://github.com/MicrosoftArchive/redis/releases
b.解壓后,在redis根目錄打開cmd界面,輸入:redis-server.exe redis.windows.conf,啟動(dòng)redis(關(guān)閉cmd窗口即停止)
2.使用
a.創(chuàng)建SpringBoot工程,選擇maven依賴
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
.....
</dependencies>
b.配置 application.yml 配置文件
server:
port: 8080
spring:
# redis相關(guān)配置
redis:
database: 0
host: localhost
port: 6379
password:
jedis:
pool:
# 連接池最大連接數(shù)(使用負(fù)值表示沒有限制)
max-active: 8
# 連接池最大阻塞等待時(shí)間(使用負(fù)值表示沒有限制)
max-wait: -1ms
# 連接池中的最大空閑連接
max-idle: 5
# 連接池中的最小空閑連接
min-idle: 0
# 連接超時(shí)時(shí)間(毫秒)默認(rèn)是2000ms
timeout: 2000ms
# thymeleaf熱更新
thymeleaf:
cache: false
c.創(chuàng)建RedisConfig配置類
@Configuration
@EnableCaching //開啟緩存
public class RedisConfig {
/**
* 緩存管理器
* @param redisConnectionFactory
* @return
*/
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
// 生成一個(gè)默認(rèn)配置,通過config對象即可對緩存進(jìn)行自定義配置
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
// 設(shè)置緩存的默認(rèn)過期時(shí)間,也是使用Duration設(shè)置
config = config.entryTtl(Duration.ofMinutes(30))
// 設(shè)置 key為string序列化
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
// 設(shè)置value為json序列化
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer()))
// 不緩存空值
.disableCachingNullValues();
// 對每個(gè)緩存空間應(yīng)用不同的配置
Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
configMap.put("userCache", config.entryTtl(Duration.ofSeconds(60)));
// 使用自定義的緩存配置初始化一個(gè)cacheManager
RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory)
//默認(rèn)配置
.cacheDefaults(config)
// 特殊配置(一定要先調(diào)用該方法設(shè)置初始化的緩存名,再初始化相關(guān)的配置)
.initialCacheNames(configMap.keySet())
.withInitialCacheConfigurations(configMap)
.build();
return cacheManager;
}
/**
* Redis模板類redisTemplate
* @param factory
* @return
*/
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
// key采用String的序列化方式
template.setKeySerializer(new StringRedisSerializer());
// hash的key也采用String的序列化方式
template.setHashKeySerializer(new StringRedisSerializer());
// value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer());
// hash的value序列化方式采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer());
return template;
}
/**
* json序列化
* @return
*/
private RedisSerializer<Object> jackson2JsonRedisSerializer() {
//使用Jackson2JsonRedisSerializer來序列化和反序列化redis的value值
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
//json轉(zhuǎn)對象類,不設(shè)置默認(rèn)的會(huì)將json轉(zhuǎn)成hashmap
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(mapper);
return serializer;
}
}
d.創(chuàng)建entity實(shí)體類
public class User implements Serializable {
private int id;
private String userName;
private String userPwd;
public User(){}
public User(int id, String userName, String userPwd) {
this.id = id;
this.userName = userName;
this.userPwd = userPwd;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPwd() {
return userPwd;
}
public void setUserPwd(String userPwd) {
this.userPwd = userPwd;
}
}
e.創(chuàng)建Service
@Service
public class UserService {
//查詢:先查緩存是是否有,有則直接取緩存中數(shù)據(jù),沒有則運(yùn)行方法中的代碼并緩存
@Cacheable(value = "userCache", key = "'user:' + #userId")
public User getUser(int userId) {
System.out.println("執(zhí)行此方法,說明沒有緩存");
return new User(userId, "用戶名(get)_" + userId, "密碼_" + userId);
}
//添加:運(yùn)行方法中的代碼并緩存
@CachePut(value = "userCache", key = "'user:' + #user.id")
public User addUser(User user){
int userId = user.getId();
System.out.println("添加緩存");
return new User(userId, "用戶名(add)_" + userId, "密碼_" + userId);
}
//刪除:刪除緩存
@CacheEvict(value = "userCache", key = "'user:' + #userId")
public boolean deleteUser(int userId){
System.out.println("刪除緩存");
return true;
}
@Cacheable(value = "common", key = "'common:user:' + #userId")
public User getCommonUser(int userId) {
System.out.println("執(zhí)行此方法,說明沒有緩存(測試公共配置是否生效)");
return new User(userId, "用戶名(common)_" + userId, "密碼_" + userId);
}
}
f.創(chuàng)建Controller
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
@RequestMapping("/getUser")
public User getUser(int userId) {
return userService.getUser(userId);
}
@RequestMapping("/addUser")
public User addUser(User user){
return userService.addUser(user);
}
@RequestMapping("/deleteUser")
public boolean deleteUser(int userId){
return userService.deleteUser(userId);
}
@RequestMapping("/getCommonUser")
public User getCommonUser(int userId) {
return userService.getCommonUser(userId);
}
}
@Controller
public class HomeController {
//默認(rèn)頁面
@RequestMapping("/")
public String login() {
return "test";
}
}
g.在 templates 目錄下,寫書 test.html 頁面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<style type="text/css">
.row{
margin:10px 0px;
}
.col{
display: inline-block;
margin:0px 5px;
}
</style>
</head>
<body>
<div>
<h1>測試</h1>
<div class="row">
<label>用戶ID:</label><input id="userid-input" type="text" name="userid"/>
</div>
<div class="row">
<div class="col">
<button id="getuser-btn">獲取用戶</button>
</div>
<div class="col">
<button id="adduser-btn">添加用戶</button>
</div>
<div class="col">
<button id="deleteuser-btn">刪除用戶</button>
</div>
<div class="col">
<button id="getcommonuser-btn">獲取用戶(common)</button>
</div>
</div>
<div class="row" id="result-div"></div>
</div>
</body>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
$(function() {
$("#getuser-btn").on("click",function(){
var userId = $("#userid-input").val();
$.ajax({
url: "/user/getUser",
data: {
userId: userId
},
dataType: "json",
success: function(data){
$("#result-div").text("id[" + data.id + ", userName[" + data.userName + "], userPwd[" + data.userPwd + "]");
},
error: function(e){
$("#result-div").text("系統(tǒng)錯(cuò)誤!");
},
})
});
$("#adduser-btn").on("click",function(){
var userId = $("#userid-input").val();
$.ajax({
url: "/user/addUser",
data: {
id: userId
},
dataType: "json",
success: function(data){
$("#result-div").text("id[" + data.id + ", userName[" + data.userName + "], userPwd[" + data.userPwd + "]");
},
error: function(e){
$("#result-div").text("系統(tǒng)錯(cuò)誤!");
},
})
});
$("#deleteuser-btn").on("click",function(){
var userId = $("#userid-input").val();
$.ajax({
url: "/user/deleteUser",
data: {
userId: userId
},
dataType: "json",
success: function(data){
$("#result-div").text(data);
},
error: function(e){
$("#result-div").text("系統(tǒng)錯(cuò)誤!");
},
})
});
$("#getcommonuser-btn").on("click",function(){
var userId = $("#userid-input").val();
$.ajax({
url: "/user/getCommonUser",
data: {
userId: userId
},
dataType: "json",
success: function(data){
$("#result-div").text("id[" + data.id + ", userName[" + data.userName + "], userPwd[" + data.userPwd + "]");
},
error: function(e){
$("#result-div").text("系統(tǒng)錯(cuò)誤!");
},
})
});
});
</script>
</html>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java通過URL獲取公眾號(hào)文章生成HTML的方法
這篇文章主要介紹了Java通過URL獲取公眾號(hào)文章生成HTML的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12
Windows下將JAVA?jar注冊成windows服務(wù)的方法
這篇文章主要介紹了Windows下將JAVA?jar注冊成windows服務(wù)的方法,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-07-07
IntelliJ IDEA 2021.1 EAP 4 發(fā)布:字體粗細(xì)可調(diào)整Git commit template 支持
這篇文章主要介紹了IntelliJ IDEA 2021.1 EAP 4 發(fā)布:字體粗細(xì)可調(diào)整,Git commit template 支持,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-02-02
SpringBoot實(shí)現(xiàn)模塊日志入庫的項(xiàng)目實(shí)踐
本文主要介紹了SpringBoot實(shí)現(xiàn)模塊日志入庫的項(xiàng)目實(shí)踐,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-04-04

