本文将为大家详细介绍SpringBoot集成springcache和redis的方法,内容详细步骤清晰,细节处理妥当,希望大家通过这篇文章有所收获。
创新互联公司专注于沙雅网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供沙雅营销型网站建设,沙雅网站制作、沙雅网页设计、沙雅网站官网定制、小程序定制开发服务,打造沙雅网络公司原创品牌,更为您提供沙雅网站排名全网营销落地服务。
添加service.UserService接口,再创建实现类service.impl.UserServiceimpl,记得实现类要加上@Service注解。并实现user的增删改查功能。同时将Controller的调用改成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);
}
}
具体配置如下,其中一个是操作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 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 redisTemplate(RedisConnectionFactory factory) {
RedisTemplate template = new RedisTemplate();
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引入的依赖可以不用引入
org.springframework.boot
spring-boot-starter-cache
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的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读。