本文將為大家詳細(xì)介紹SpringBoot集成springcache和redis的方法,內(nèi)容詳細(xì)步驟清晰,細(xì)節(jié)處理妥當(dāng),希望大家通過這篇文章有所收獲。
創(chuàng)新互聯(lián)公司專注于沙雅網(wǎng)站建設(shè)服務(wù)及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗(yàn)。 熱誠為您提供沙雅營銷型網(wǎng)站建設(shè),沙雅網(wǎng)站制作、沙雅網(wǎng)頁設(shè)計(jì)、沙雅網(wǎng)站官網(wǎng)定制、小程序定制開發(fā)服務(wù),打造沙雅網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供沙雅網(wǎng)站排名全網(wǎng)營銷落地服務(wù)。
添加service.UserService接口,再創(chuàng)建實(shí)現(xiàn)類service.impl.UserServiceimpl,記得實(shí)現(xiàn)類要加上@Service注解。并實(shí)現(xiàn)user的增刪改查功能。同時(shí)將Controller的調(diào)用改成UserService。
org.springframework.boot
spring-boot-starter-data-redis
org.springframework.boot
spring-boot-starter-cache
org.apache.commons
commons-pool2
server:
port: 8090
# 掃描mapper.xml文件
mybatis:
mapper-locations:
- classpath:mapping/*.xml
spring:
application:
name: springboot-ssm
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.MySQL.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/springboot?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: 123zxc
redis:
host: 127.0.0.1
port: 6379
password: 123zxc
database: 0
lettuce:
pool:
max-active: 32
max-wait: 300ms
max-idle: 16
min-idle: 8
@Service
public class UserServiceImpl implements UserService {
private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
@Resource
private UserMapper userMapper;
@Override
@Cacheable(value = "user:id",key = "#id")
public User getOneUser(int id) {
logger.info("get one go mysql ...");
return userMapper.selectByPrimaryKey(id);
}
@Cacheable(value = "user:list")
@Override
public List findAll() {
logger.info("find all go mysql ...");
return userMapper.list();
}
@CacheEvict(value = "user:list",allEntries = true)
@Override
public int add(User user) {
return userMapper.insert(user);
}
@Caching(
evict = {
@CacheEvict(value = "user:id", key = "#user.id"),
@CacheEvict(value = "user:list", allEntries = true)
}
)
@Override
public int update(User user) {
return userMapper.updateByPrimaryKey(user);
}
@Caching(
evict = {
@CacheEvict(value = "user:id", key = "#id"),
@CacheEvict(value = "user:list", allEntries = true)
}
)
@Override
public int delete(int id) {
return delete(id);
}
}
具體配置如下,其中一個(gè)是操作redis 的RedisTemplate,一個(gè)是緩存使用的CacheManager,其中修改了序列化方式,所以要把原來的緩存清空。
@Component
@Configuration
@ConfigurationProperties("spring.cache.redis")
public class RedisConfig extends CachingConfigurerSupport {
private Duration timeToLive = Duration.ofMinutes(30);
public void setTimeToLive(Duration timeToLive) {
this.timeToLive = timeToLive;
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisSerializer redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//解決查詢緩存轉(zhuǎn)換異常的問題
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// 配置序列化(解決亂碼的問題)
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(timeToLive)
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
return cacheManager;
}
//RedisTemplate配置
@Bean
@SuppressWarnings("all")
public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
RedisTemplate template = new RedisTemplate();
template.setConnectionFactory(factory);
//配置事務(wù)
template.setEnableTransactionSupport(true);
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);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
Springboot 操作redis引入的依賴可以不用引入
org.springframework.boot
spring-boot-starter-cache
SpringBoot Redis提供一個(gè)強(qiáng)大的模版操作redis,它就是RedisTemplate,使用它可以很方便的操作redis 的五大數(shù)據(jù)類型。下面我們寫一個(gè)測(cè)試類使用RedisTemplate的相關(guān)API。
首先把引入spring-boot-starter-test依賴,同時(shí)去掉junit依賴,否則會(huì)報(bào)錯(cuò)!
在test/java/xyz.java1024 下創(chuàng)建RedisTemplateTest測(cè)試類,加上@RunWith(SpringRunner.class)
@SpringBootTest(classes = RedisApp.class)注解,指定啟動(dòng)類作用是讀取配置信息。具體代碼如下:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = RedisApp.class)
public class RedisTemplateTest {
@Resource
private RedisTemplate redisTemplate;
/**
*
* 介紹 如何使用 redisTemplate 操作String List Set ZSet Hash五種數(shù)據(jù)類型
* 本測(cè)試只 使用了部分常用的 api,如在集合等復(fù)雜數(shù)據(jù)類型 有更多的api 實(shí)現(xiàn)更加強(qiáng)大的功能,查閱相關(guān)文檔即可!
*
*/
/**
* String 類型set
*/
@Test
public void testSet() {
redisTemplate.opsForValue().set("test","this is test");
}
/**
* String 類型get
*/
@Test
public void testGet() {
Object test = redisTemplate.opsForValue().get("test");
System.out.println("test = " + test);
}
/**
* 添加元素
*/
@Test
public void testLSet() {
redisTemplate.opsForList().leftPush("testList","testList1");
}
/**
* 獲取List 的所有元素
*/
@Test
public void testLGet() {
List testList = redisTemplate.opsForList().range("testList", 0, -1);
System.out.println("testList = " + testList);
}
/**
* Set類型 set
*/
@Test
public void testSSet() {
redisTemplate.opsForSet().add("testSet","testSet1");
}
/**
* Set 類型get
*/
@Test
public void testSGet() {
Set testSet = redisTemplate.opsForSet().members("testSet");
System.out.println("testSet = " + testSet);
}
/**
* hash set
*/
@Test
public void testHSet() {
redisTemplate.opsForHash().put("testHash","value1","key1");
redisTemplate.opsForHash().put("testHash","value2","key2");
}
/**
* hash get
*/
@Test
public void testHget() {
Object o = redisTemplate.opsForHash().get("testHash", "value1");
System.out.println("o = " + o);
}
/**
* Zset set
*/
@Test
public void testZSet() {
redisTemplate.opsForZSet().add("java1024","SpringBoot",10);
redisTemplate.opsForZSet().add("java1024","SpringCloud",3);
}
/**
* Zset get
*/
@Test
public void testZGet() {
// 正序
Set all = redisTemplate.opsForZSet().range("java1024", 0, -1);
System.out.println("all = " + all);
//反序
Set reverseRange = redisTemplate.opsForZSet().reverseRange("java1024", 0, -1);
System.out.println("reverseRange = " + reverseRange);
}
}
看完這篇文章,你們學(xué)會(huì)SpringBoot集成springcache和redis的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀。