关于redis连接池的实战
- pom层
- controller层
- service层
- Redis配置类
- hash取余封装类
pom层
org.springframework.boot
spring-boot-starter-web
redis.clients
jedis
controller层
@RestController
public class RedisController {
@Autowired
private RedisService redisService;
@RequestMapping(value="/set")
public String setData(String key,String value){
redisService.setData(key,value);
return "success";
}
}
service层
@Service
public class RedisService {
@Autowired
private ShardedJedisPool pool;
public void setData(String key, String value) {
//获取资源
ShardedJedis resource = pool.getResource();
try{
resource.set(key,value);
}catch (Exception e){
e.printStackTrace();
}finally{
if(resource!=null){
resource.close();
}
}
}
}
Redis配置类
@Configuration
public class RedisConfig {
//TODO 读取properties属性实现数据的追加
//请将这个初始化方法中的所有set进的值替换成读取的属性
@Value("${redis.jedis.nodes}")
private List nodes; //["10.0.0.0:8080","10.0.0.1:8080"]
@Bean
public ShardedJedisPool initPool(){
//需要两个对象 config nodes
JedisPoolConfig config=new JedisPoolConfig();
config.setMaxIdle(10);
config.setMinIdle(2);
config.setMaxTotal(50);
List nodes=new ArrayList<>();
nodes.add(new JedisShardInfo("192.168.184.130",6379));
nodes.add(new JedisShardInfo("192.168.184.130",6380));
nodes.add(new JedisShardInfo("192.168.184.130",6381));
return new ShardedJedisPool(config,nodes);
}
}
hash取余封装类
public class MyShardedJedis {
//准备分片集群
private List nodes;//测试会有3个元素 6379(0) 6380(1) 6381(2)
//构造方法传递正在使用的分片集群
public MyShardedJedis(List nodes){
this.nodes=nodes;
}
//封装一个方法 getShard 利用分片节点 nodes计算hash取余
public Jedis getShard(String key){
//利用key值做hash取余计算 得到key在当前集群中对应哪个节点
if(key==null){
throw new RuntimeException("你的key是空的");
}
int index=(key.hashCode()&Integer.MAX_VALUE)%nodes.size();//0,1,2
return nodes.get(index);
}
//挨个封装jedis的api 形成分布式计算
//set get exists ttl
public void set(String key,String value){
//获取分片,直到key值对应哪个节点
Jedis shard = getShard(key);
shard.set(key,value);
}
public String get(String key){
Jedis shard = getShard(key);
return shard.get(key);
}
public boolean exists(String key){
Jedis shard = getShard(key);
return shard.exists(key);
}
public Long ttl(String key){
Jedis shard = getShard(key);
return shard.ttl(key);
}
//TODO
}