SpringBoot 集成Redis +SpringCache做緩存
一.給user加緩存
1.首先創(chuàng)建springboot-redis-cache模塊,并把springboot-restful-api的內容復制過來秧了。
2.修改三層架構坦敌,即加service層
添加service.UserService接口欺冀,再創(chuàng)建實現(xiàn)類service.impl.UserServiceimpl贮庞,記得實現(xiàn)類要加上@Service注解蹄葱。并實現(xiàn)user的增刪改查功能氏义。同時將Controller的調用改成UserService。
3.加入redis cache pool等依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
4.配置redis
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
5.啟動類加上@EnableCaching注解
6.Service加緩存
@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<User> 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);
}
}
以上SpringBoot默認對redis 的配置图云,如果我們想修改redis的配置惯悠,如序列化方式、默認過期時間等等竣况。則需要我們創(chuàng)建RedisConfig.java配置類克婶。
二.手動配置RedisConfig.java
具體配置如下,其中一個是操作redis 的RedisTemplate,一個是緩存使用的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<String> redisSerializer = new StringRedisSerializer();
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);
// 配置序列化(解決亂碼的問題)
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<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(factory);
//配置事務
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
Springboot 操作redis引入的依賴可以不用引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
1.說明
SpringBoot Redis提供一個強大的模版操作redis,它就是RedisTemplate筋岛,使用它可以很方便的操作redis 的五大數(shù)據(jù)類型娶视。下面我們寫一個測試類使用RedisTemplate的相關API。
首先把引入spring-boot-starter-test依賴泉蝌,同時去掉junit依賴歇万,否則會報錯!
2.添加RedisTemplateTest
在test/java/xyz.java1024 下創(chuàng)建RedisTemplateTest測試類勋陪,加上@RunWith(SpringRunner.class)
@SpringBootTest(classes = RedisApp.class)注解贪磺,指定啟動類作用是讀取配置信息。具體代碼如下:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = RedisApp.class)
public class RedisTemplateTest {
@Resource
private RedisTemplate redisTemplate;
/**
*
* 介紹 如何使用 redisTemplate 操作String List Set ZSet Hash五種數(shù)據(jù)類型
* 本測試只 使用了部分常用的 api诅愚,如在集合等復雜數(shù)據(jù)類型 有更多的api 實現(xià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);
}
}
總結
操作Redis不依賴SpringCache违孝,實現(xiàn)SpringCache也不止Redis刹前,也可以用ehCache做緩存!只是現(xiàn)在主流還是用Redis做緩存雌桑。