SpringBoot进阶教程(二十四)整合Redis
缓存现在几乎是所有中大型网站都在用的必杀技,合理的利用缓存不仅能够提升网站访问速度,还能大大降低数据库的压力。Redis提供了键过期功能,也提供了灵活的键淘汰策略,所以,现在Redis用在缓存的场合非常多。
之前有两篇博文(centos安装Redis 和 Redis五大数据类型的常用操作),分别介绍了Redis的安装和Redis的常用操作。今天主要介绍介绍springboot整合Redis。
v应用场景
现在公司做的项目都偏重论坛/社区/社交类产品,所以对Redis的实用场景主要集中在排行榜,最新/最热内容,Redis提供的有序集合数据类构能实现各种复杂的排行榜应用。还有点赞、踩、关注/被关注、共同好友等是社交网站的基本功能,社交网站的访问量通常来说比较大,而且传统的关系数据库类型不适合存储这种类型的数据,Redis提供的哈希、集合等数据结构能很方便的的实现这些功能。
还有很多应用场景,比如分布式会话和分布式锁(分布式锁感兴趣的可以看我之前的一篇文章《Java分布式锁,搞懂分布式锁实现看这篇文章就对了》)等等,总之越来越广泛。
v搭建Redis
1.1. 引入Redis
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--<dependency>-->
<!--<groupId>redis.clients</groupId>-->
<!--<artifactId>jedis</artifactId>-->
<!--<version>2.9.0</version>-->
<!--</dependency>-->
注意redis.clients是我本地调试测试用的,可以忽略。
1.2. 添加RedisCacheConfig
package com.demo.Redis; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; import java.util.concurrent.CountDownLatch; /**
* Created by toutou on 2019/1/20.
*/
@Configuration
@EnableCaching
public class RedisCacheConfig {
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
MessageListenerAdapter listenerAdapter) { RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(listenerAdapter, new PatternTopic("chat")); return container;
} @Bean
MessageListenerAdapter listenerAdapter(Receiver receiver) {
return new MessageListenerAdapter(receiver, "receiveMessage");
} @Bean
Receiver receiver(CountDownLatch latch) {
return new Receiver(latch);
} @Bean
CountDownLatch latch() {
return new CountDownLatch(1);
} @Bean
StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
return new StringRedisTemplate(connectionFactory);
} public class Receiver { private CountDownLatch latch; @Autowired
public Receiver(CountDownLatch latch) {
this.latch = latch;
} public void receiveMessage(String message) {
latch.countDown();
}
}
}
可以按需添加,也可以按需忽略。
1.3. 添加Redis配置,修改application.properties
# ----- Redis -------- #
# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=10.168.11.129
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=5000
1.4. 添加Service
package com.demo.service; import com.demo.pojo.UserDetails; /**
* Created by toutou on 2018/10/15.
*/
public interface UserService {
UserDetails getUserDetailsByUid(int uid);
String getUserNameById(Integer uid);
void setUserNameById(Integer uid, String userName);
}
UserServiceImpl
package com.demo.service; import com.demo.dao.UserDetailsMapper;
import com.demo.dao.UserPositionMapper;
import com.demo.pojo.UserDetails;
import com.demo.pojo.UserPosition;
import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service; import java.math.BigDecimal;
import java.util.List; /**
* Created by toutou on 2018/10/15.
*/
@Service
public class UserServiceImpl implements UserService{
@Autowired
UserDetailsMapper userDetailsMapper; @Autowired
UserPositionMapper userPositionMapper; @Autowired
StringRedisTemplate template; static final String KEY_USER_INFO__NAME = "com_demo_user_info_007_%s"; public String getUserNameById(Integer uid){
String userName = "未知用户";
try {
userName = template.opsForValue().get(String.format(KEY_USER_INFO__NAME, uid));
if (Strings.isNullOrEmpty(userName)) {
// Redis中没有就读数据库
UserDetails userDetails = getUserDetailsByUid(uid);
if (userDetails != null && !Strings.isNullOrEmpty(userDetails.getCity())) {
userName = userDetails.getCity();
}
}
}catch(Exception e){
System.out.println(e.toString());
} return userName; } public void setUserNameById(Integer uid, String userName){
template.opsForValue().set(String.format(KEY_USER_INFO__NAME, uid), userName);
} public UserDetails getUserDetailsByUid(int uid){
return userDetailsMapper.getUserDetailsByUid(uid);
} }
1.5. 添加RedisController
package com.demo.controller; import com.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis; /**
* Created by toutou on 2019/1/20.
*/
@RestController
@Slf4j
public class RedisController { @Autowired
UserService userService; @RequestMapping(value = "/getusernamebyid")
public String getUserNameById(Integer uid)
{
return userService.getUserNameById(uid);
} @RequestMapping(value = "/setusernamebyid")
public String setUserNameById(Integer uid, String uname)
{
userService.setUserNameById(uid, uname);
return "设置成功";
} @RequestMapping(value = "/jedistest")
public String jedisTest(){
// 创建一个jedis对象
Jedis jedis = new Jedis("ip", 6379);
// 直接调用jedis对象的方法,方法名称和redis的命令一致
jedis.set("key1", "test01");
String key1 = jedis.get("key1");
System.out.println(key1 + " " + key1);
// 关闭jedis
jedis.close();
return key1;
}
}
注意jedisTest是我本地调试测试用的,可以忽略。
vRedis测试效果
v源码地址
https://github.com/toutouge/javademosecond/tree/master/hellospringboot
作 者:请叫我头头哥
出 处:http://www.cnblogs.com/toutou/
关于作者:专注于基础平台的项目开发。如有问题或建议,请多多赐教!
版权声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。
特此声明:所有评论和私信都会在第一时间回复。也欢迎园子的大大们指正错误,共同进步。或者直接私信我
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。您的鼓励是作者坚持原创和持续写作的最大动力!
SpringBoot进阶教程(二十四)整合Redis的更多相关文章
- SpringBoot进阶教程(二十九)整合Redis 发布订阅
SUBSCRIBE, UNSUBSCRIBE 和 PUBLISH 实现了 发布/订阅消息范例,发送者 (publishers) 不用编程就可以向特定的接受者发送消息 (subscribers). Ra ...
- SpringBoot进阶教程(二十八)整合Redis事物
Redis默认情况下,事务支持被禁用,必须通过设置setEnableTransactionSupport(true)为使用中的每个redistplate显式启用.这样做会强制将当前重新连接绑定到触发m ...
- SpringBoot进阶教程(二十六)整合Redis之共享Session
集群现在越来越常见,当我们项目搭建了集群,就会产生session共享问题.因为session是保存在服务器上面的.那么解决这一问题,大致有三个方案,1.通过nginx的负载均衡其中一种ip绑定来实现( ...
- SpringBoot进阶教程(二十五)整合Redis之@Cacheable、@CachePut、@CacheEvict的应用
在上一篇文章(<SpringBoot(二十四)整合Redis>)中,已经实现了Spring Boot对Redis的整合,既然已经讲到Cache了,今天就介绍介绍缓存注解.各家互联网产品现在 ...
- SpringBoot进阶教程(七十四)整合ELK
在上一篇文章<SpringBoot进阶教程(七十三)整合elasticsearch >,已经详细介绍了关于elasticsearch的安装与使用,现在主要来看看关于ELK的定义.安装及使用 ...
- SpringBoot进阶教程(六十四)注解大全
在Spring1.x时代,还没出现注解,需要大量xml配置文件并在内部编写大量bean标签.Java5推出新特性annotation,为spring的更新奠定了基础.从Spring 2.X开始spri ...
- SpringBoot进阶教程(五十九)整合Codis
上一篇博文<详解Codis安装与部署>中,详细介绍了codis的安装与部署,这篇文章主要介绍介绍springboot整合codis.如果之前看过<SpringBoot进阶教程(五十二 ...
- SpringBoot进阶教程(二十二)集成RabbitMQ---MQ实战演练
RabbitMQ是一个在AMQP基础上完成的,可复用的企业消息系统.他遵循Mozilla Public License开源协议.RabbitMQ是流行的开源消息队列系统,用erlang语言开发.Rab ...
- SpringBoot进阶教程(二十七)整合Redis之分布式锁
在之前的一篇文章(<Java分布式锁,搞懂分布式锁实现看这篇文章就对了>),已经介绍过几种java分布式锁,今天来个Redis分布式锁的demo.redis 现在已经成为系统缓存的必备组件 ...
随机推荐
- Nginx日志自动按日期存储
Nginx ("engine x") 是一个高性能的 HTTP 和 反向代理 服务器,也是一个 IMAP/POP3/SMTP 代理服务器,因它的稳定性.丰富的功能集.示例配置文件和 ...
- jQuery的学习笔记4
JQuery学习笔记3 2.9属性选择器 属性选择器就是根据元素的属性和属性值作为过滤条件,来匹配对应的DOM元素.属性选择器一般都以中括号作为起止分界符 它的形式如下: [attribute] [a ...
- UE4学习心得:蓝图间信息通信的几种方法
蓝图间通信是一个复杂关卡能否正常运行的关键,笔者在这里提供几种蓝图类之间的信息交互方法,希望能对读者有所帮助. 1.类引用 这是最直接的一种蓝图类之间的信息交互方式.首先在Editor中创建2个Act ...
- Python测试远程端口连接时间
问题 最近自己服务器访问别人的服务器,有时候会报超时错误,有时候又能够正常访问别人服务器. 思路 最开始猜测是网络不稳定造成的,但是自己没有收集什么时候超时,什么时候能正常访问别人服务器的日志,搞网络 ...
- Unity5 assetbundle笔记
Assetbundle api试验----打包选项试验--------结论:BuildAssetBundleOptions说明:------------None: 把所有以来资源到到一个包里----- ...
- 从数据库读取数据并动态生成easyui tree构结
一. 数据库表结构 二.从后台读取数据库生成easyui tree结构的树 1.TreeNode树结点类(每个结点都包含easyui tree 的基本属性信息) import java.io.Seri ...
- 通过jstack与jmap分析一次cpu打满的线上故障
一.发现问题 下面是线上机器的cpu使用率,可以看到从4月8日开始,随着时间cpu使用率在逐步增高,最终使用率达到100%导致线上服务不可用,后面重启了机器后恢复. 二.排查思路 简单分析下可能出问题 ...
- linux基础和vim基本使用
Liunx基础 1. 目录 /:根目录,一般根目录只存放目录,在linux下有且只有一个根目录.所有的东西都是从这里开始,例如:/home就是先从根目录/开始,再进入到home目录. /bin ...
- Python3之利用Cookie模拟登录
Python3之利用Cookie模拟登录 利用Cookie模拟登录步骤: 1. 在浏览器输入http://demo.bxcker.com,输入用户名和密码登录. 2.登录成功点" ...
- Python_字符串的大小写变换
''' lower().upper().capitalize().title().swapcase() 这几个方法分别用来将字符串转换为小写.大写字符串.将字符串首字母变为大写.将每个首字母变为大写以 ...