写在最后
为了这次面试,也收集了很多的面试题!
以下是部分面试题截图
| — | — |
| lock()
| Acquires the lock.
加锁,如果已经被其他线程锁住或者当前线程不能获取锁则阻塞 |
| lockInterruptibly()
| Acquires the lock unless the current thread is interrupted.
加锁,除非当前线程被打断。 |
| tryLock()
| Acquires the lock only if it is free at the time of invocation.
尝试加锁,如果已经有其他锁锁住,获取当前线程不能加锁,则返回false,加锁失败;加锁成功则返回true |
| tryLock(long time, TimeUnit unit)
| Acquires the lock if it is free within the given waiting time and the current thread has not been interrupted.
尝试在指定时间内加锁,如果已经有其他锁锁住,获取当前线程不能加锁,则返回false,加锁失败;加锁成功则返回true |
| unlock()
| Releases the lock.
解锁 |
话不多说,我们看看使用 Spring Integration
如何基于redis和zookeeper快速实现分布式锁,至于Gemfire 和 Jdbc的实现大家自行实践。
基于Redis实现
- 引入相关组件
org.springframework.boot
spring-boot-starter-integration
org.springframework.integration
spring-integration-redis
org.springframework.boot
spring-boot-starter-data-redis
- 在application.yml中添加redis的配置
spring:
redis:
host: 172.31.0.149
port: 7111
- 建立配置类,注入
RedisLockRegistry
@Configuration
public class RedisLockConfiguration {
@Bean
public RedisLockRegistry redisLockRegistry(RedisConnectionFactory redisConnectionFactory){
return new RedisLockRegistry(redisConnectionFactory, “redis-lock”);
}
}
- 编写测试代码
@RestController
@RequestMapping(“lock”)
@Log4j2
public class DistributedLockController {
@Autowired
private RedisLockRegistry redisLockRegistry;
@GetMapping(“/redis”)
public void test1() {
Lock lock = redisLockRegistry.obtain(“redis”);
try{
//尝试在指定时间内加锁,如果已经有其他锁锁住,获取当前线程不能加锁,则返回false,加锁失败;加锁成功则返回true
if(lock.tryLock(3, TimeUnit.SECONDS)){
log.info(“lock is ready”);
TimeUnit.SECONDS.sleep(5);
}
} catch (InterruptedException e) {
log.error(“obtain lock error”,e);
} finally {
lock.unlock();
}
}
}
- 测试
启动多个实例,分别访问 /lock/redis
端点,一个正常秩序业务逻辑,另外一个实例访问出现如下错误
说明第二个实例没有拿到锁,证明了分布式锁的存在。
注意,如果使用新版Springboot进行集成时需要使用Redis4版本,否则会出现下面的异常告警,主要是
unlock()
释放锁时使用了UNLINK命令,这个需要Redis4版本才能支持。
2020-05-14 11:30:24,781 WARN RedisLockRegistry:339 - The UNLINK command has failed (not supported on the Redis server?); falling back to the regular DELETE command
org.springframework.data.redis.RedisSystemException: Error in execution; nested exception is io.lettuce.core.RedisCommandExecutionException: ERR unknown command ‘UNLINK’
基于Zookeeper实现
- 引入组件
org.springframework.boot
spring-boot-starter-integration
org.springframework.integration
spring-integration-zookeeper
- 在application.yml中添加zookeeper的配置
zookeeper:
host: 172.31.0.43:2181
总结:绘上一张Kakfa架构思维大纲脑图(xmind)
其实关于Kafka,能问的问题实在是太多了,扒了几天,最终筛选出44问:基础篇17问、进阶篇15问、高级篇12问,个个直戳痛点,不知道如果你不着急看答案,又能答出几个呢?
若是对Kafka的知识还回忆不起来,不妨先看我手绘的知识总结脑图(xmind不能上传,文章里用的是图片版)进行整体架构的梳理
梳理了知识,刷完了面试,如若你还想进一步的深入学习解读kafka以及源码,那么接下来的这份《手写“kafka”》将会是个不错的选择。
-
Kafka入门
-
为什么选择Kafka
-
Kafka的安装、管理和配置
-
Kafka的集群
-
第一个Kafka程序
-
Kafka的生产者
-
Kafka的消费者
-
深入理解Kafka
-
可靠的数据传递
-
Spring和Kafka的整合
-
SpringBoot和Kafka的整合
-
Kafka实战之削峰填谷
-
数据管道和流式处理(了解即可)
片转存中…(img-Q1JPAn8D-1715344308305)]
[外链图片转存中…(img-b5xLbioj-1715344308305)]