您好,登录后才能下订单哦!
本文将为大家详细介绍SpringBoot集成springcache和redis的方法,内容详细步骤清晰,细节处理妥当,希望大家通过这篇文章有所收获。
添加service.UserService接口,再创建实现类service.impl.UserServiceimpl,记得实现类要加上@Service注解。并实现user的增删改查功能。同时将Controller的调用改成UserService。
<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>
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<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);
}
}
具体配置如下,其中一个是操作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引入的依赖可以不用引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
SpringBoot Redis提供一个强大的模版操作redis,它就是RedisTemplate,使用它可以很方便的操作redis 的五大数据类型。下面我们写一个测试类使用RedisTemplate的相关API。
首先把引入spring-boot-starter-test依赖,同时去掉junit依赖,否则会报错!
在test/java/xyz.java1024 下创建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五种数据类型
* 本测试只 使用了部分常用的 api,如在集合等复杂数据类型 有更多的api 实现更加强大的功能,查阅相关文档即可!
*
*/
/**
* 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);
}
}
看完这篇文章,你们学会SpringBoot集成springcache和redis的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。