spring boot 使用 redis 缓存
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了spring boot 使用 redis 缓存,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2533字,纯文字阅读大概需要4分钟。
内容图文
spring boot redis 使用 1Redis:
Redis 是完全开源免费的,遵守BSD协议,是一个高性能的key-value数据库。
Redis 与其他 key - value 缓存产品有以下三个特点:
Redis支持数据的持久化,可以将内存中的数据保存在磁盘中,重启的时候可以再次加载进行使用。
Redis不仅仅支持简单的key-value类型的数据,同时还提供list,set,zset,hash等数据结构的存储。
Redis支持数据的备份,即master-slave模式的数据备份。
spring boot 中如何使用:
引入依赖 pom.xml
<!-- redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
配置redis
#redis配置
#Redis服务器地址
spring.redis.host=192.168.5.10
#Redis服务器连接端口
spring.redis.port=6379
#Redis数据库索引(默认为0)
spring.redis.database=4
#连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=50
#连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=3000
#连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=20
#连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=2
#连接超时时间(毫秒)
spring.redis.timeout=5000修改启动类 添加 @EnableCaching 注解
@RestController@SpringBootApplication
' title='br/>@SpringBootApplication
' ref='nofollow'>br/>@SpringBootApplication
@MapperScan("com.example.demo.dao.mybatis")@EnableCaching
' title='br/>@EnableCaching
' ref='nofollow'>br/>@EnableCaching
public class DemoApplication实体类添加 序列化支持
public class User implements Serializable
在 service 上加上缓存注解
@Service public class MybatisUserService { @Autowired UserMapper userDao; public int add(User user){ return userDao.add(user); } public int update(User user){ return userDao.update(user); } @Cacheable(value = "user-key") public User getById(long id){ System.out.println("从数据库获取数据"); return userDao.findUserById(id); } }
----------------自动加入缓存结束------------
手动操作缓存:
@Component
public class RedisUtil {
@Autowired
private RedisTemplate<String, String> redisTemplate;
/**
* 读取缓存
*
* @param key
* @return
*/
public String get(final String key) {
return redisTemplate.opsForValue().get(key);
}
/**
* 写入缓存
*/
public boolean set(final String key, String value) {
boolean result = false;
try {
redisTemplate.opsForValue().set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 更新缓存
*/
public boolean getAndSet(final String key, String value) {
boolean result = false;
try {
redisTemplate.opsForValue().getAndSet(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 删除缓存
*/
public boolean delete(final String key) {
boolean result = false;
try {
redisTemplate.delete(key);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
redis 简单的操作介绍完成
原文:https://blog.51cto.com/5013162/2404306
内容总结
以上是互联网集市为您收集整理的spring boot 使用 redis 缓存全部内容,希望文章能够帮你解决spring boot 使用 redis 缓存所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。