詳解Spring Boot使用redis實(shí)現(xiàn)數(shù)據(jù)緩存
基于spring Boot 1.5.2.RELEASE版本,一方面驗(yàn)證與Redis的集成方法,另外了解使用方法。
集成方法
1、配置依賴
修改pom.xml,增加如下內(nèi)容。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、配置Redis
修改application.yml,增加如下內(nèi)容。
spring:
redis:
host: localhost
port: 6379
pool:
max-idle: 8
min-idle: 0
max-active: 8
max-wait: -1
3、配置Redis緩存
package net.jackieathome.cache;
import java.lang.reflect.Method;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
@Configuration
@EnableCaching // 啟用緩存特性
public class RedisConfig extends CachingConfigurerSupport {
// 緩存數(shù)據(jù)時(shí)Key的生成器,可以依據(jù)業(yè)務(wù)和技術(shù)場(chǎng)景自行定制
// @Bean
// public KeyGenerator customizedKeyGenerator() {
// return new KeyGenerator() {
// @Override
// public Object generate(Object target, Method method, Object... params) {
// StringBuilder sb = new StringBuilder();
// sb.append(target.getClass().getName());
// sb.append(method.getName());
// for (Object obj : params) {
// sb.append(obj.toString());
// }
// return sb.toString();
// }
// };
//
// }
// 定制緩存管理器的屬性,默認(rèn)提供的CacheManager對(duì)象可能不能滿足需要
// 因此建議依賴業(yè)務(wù)和技術(shù)上的需求,自行做一些擴(kuò)展和定制
@Bean
public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
redisCacheManager.setDefaultExpiration(300);
return redisCacheManager;
}
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
驗(yàn)證集成后的效果
考慮到未來參與的項(xiàng)目基于MyBatis實(shí)現(xiàn)數(shù)據(jù)庫(kù)訪問,而利用緩存,可有效改善Web頁(yè)面的交互體驗(yàn),因此設(shè)計(jì)了如下兩個(gè)驗(yàn)證方案。
方案一
在訪問數(shù)據(jù)庫(kù)的數(shù)據(jù)對(duì)象上增加緩存注解,定義緩存策略。從測(cè)試效果看,緩存有效。
1、頁(yè)面控制器
package net.jackieathome.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import net.jackieathome.bean.User;
import net.jackieathome.dao.UserDao;
import net.jackieathome.db.mapper.UserMapper;
@RestController
public class UserController {
@Autowired
private UserDao userDao;
@RequestMapping(method = RequestMethod.GET, value = "/user/id/{id}")
public User findUserById(@PathVariable("id") String id) {
return userDao.findUserById(id);
}
@RequestMapping(method = RequestMethod.GET, value = "/user/create")
public User createUser() {
long time = System.currentTimeMillis() / 1000;
String id = "id" + time;
User user = new User();
user.setId(id);
userDao.createUser(user);
return userDao.findUserById(id);
}
}
2、Mapper定義
package net.jackieathome.db.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import net.jackieathome.bean.User;
@Mapper
public interface UserMapper {
void createUser(User user);
User findUserById(@Param("id") String id);
}
3、數(shù)據(jù)訪問對(duì)象
package net.jackieathome.dao;
import java.util.ArrayList;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import net.jackieathome.bean.User;
import net.jackieathome.db.mapper.UserMapper;
@Component
@CacheConfig(cacheNames = "users")
@Transactional
public class UserDao {
private static final Logger LOG = LoggerFactory.getLogger(UserDao.class);
@Autowired
private UserMapper userMapper;
@CachePut(key = "#p0.id")
public void createUser(User user) {
userMapper.createUser(user);
LOG.debug("create user=" + user);
}
@Cacheable(key = "#p0")
public User findUserById(@Param("id") String id) {
LOG.debug("find user=" + id);
return userMapper.findUserById(id);
}
}
方案二
直接在Mapper定義上增加緩存注解,控制緩存策略。從測(cè)試效果看,緩存有效,相比于方案一,測(cè)試代碼更加簡(jiǎn)潔一些。
1、頁(yè)面控制器
package net.jackieathome.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import net.jackieathome.bean.User;
import net.jackieathome.dao.UserDao;
import net.jackieathome.db.mapper.UserMapper;
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@RequestMapping(method = RequestMethod.GET, value = "/user/id/{id}")
public User findUserById(@PathVariable("id") String id) {
return userMapper.findUserById(id);
}
@RequestMapping(method = RequestMethod.GET, value = "/user/create")
public User createUser() {
long time = System.currentTimeMillis() / 1000;
String id = "id" + time;
User user = new User();
user.setId(id);
userMapper.createUser(user);
return userMapper.findUserById(id);
}
}
2、Mapper定義
package net.jackieathome.db.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import net.jackieathome.bean.User;
@CacheConfig(cacheNames = "users")
@Mapper
public interface UserMapper {
@CachePut(key = "#p0.id")
void createUser(User user);
@Cacheable(key = "#p0")
User findUserById(@Param("id") String id);
}
總結(jié)
上述兩個(gè)測(cè)試方案并沒有優(yōu)劣之分,僅是為了驗(yàn)證緩存的使用方法,體現(xiàn)了不同的控制粒度,在實(shí)際的項(xiàng)目開發(fā)過程中,需要依據(jù)實(shí)際情況做不同的決斷。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解java如何實(shí)現(xiàn)帶RequestBody傳Json參數(shù)的GET請(qǐng)求
在調(diào)試Fate平臺(tái)時(shí),遇到了一個(gè)奇葩的接口類型,該接口為Get方式,入?yún)⑹且粋€(gè)json類型在body中傳遞,使用body中傳參的話為什么不用POST請(qǐng)求而使用了GET請(qǐng)求,下面我們就來深入研究一下2024-02-02
SocketIo+SpringMvc實(shí)現(xiàn)文件的上傳下載功能
這篇文章主要介紹了SocketIo+SpringMvc實(shí)現(xiàn)文件的上傳下載功能,socketIo不僅可以用來做聊天工具,也可以實(shí)現(xiàn)局域網(wǎng)。文中給出了實(shí)現(xiàn)代碼,需要的朋友可以參考下2018-08-08
SpringCloud feign微服務(wù)調(diào)用之間的異常處理方式
這篇文章主要介紹了SpringCloud feign微服務(wù)調(diào)用之間的異常處理方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06
Java使用dom4j實(shí)現(xiàn)對(duì)xml簡(jiǎn)單的增刪改查操作示例
這篇文章主要介紹了Java使用dom4j實(shí)現(xiàn)對(duì)xml簡(jiǎn)單的增刪改查操作,結(jié)合實(shí)例形式詳細(xì)分析了Java使用dom4j實(shí)現(xiàn)對(duì)xml簡(jiǎn)單的增刪改查基本操作技巧與相關(guān)注意事項(xiàng),需要的朋友可以參考下2020-05-05
JSP服務(wù)器端和前端出現(xiàn)亂碼問題解決方案
這篇文章主要介紹了JSP服務(wù)器端和前端出現(xiàn)亂碼問題解決方案,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-02-02
濫用@PathVariable導(dǎo)致bug原因分析解決
這篇文章主要為大家介紹了濫用@PathVariable導(dǎo)致bug原因分析解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12

