一、java操作redis集群
Java操作集群:
Set jedisClusterNodes=new HashSet();
jedisClusterNodes.add(new HostAndPort("192.168.1.124",7001));
jedisClusterNodes.add(new HostAndPort("192.168.1.124",7002));
jedisClusterNodes.add(new HostAndPort("192.168.1.124",7003));
jedisClusterNodes.add(new HostAndPort("192.168.1.124",7004));
jedisClusterNodes.add(new HostAndPort("192.168.1.124",7005));
jedisClusterNodes.add(new HostAndPort("192.168.1.124",7006));
JedisPoolConfig jedisPoolConfig=new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(100);
jedisPoolConfig.setMaxIdle(20);
jedisPoolConfig.setMaxWaitMillis(-1);
jedisPoolConfig.setTestOnBorrow(true);
//节点,超时时间,最多重定向次数,链接池
JedisCluster jedisCluster=new JedisCluster(jedisClusterNodes,6000,1000,jedisPoolConfig);
System.out.println(jedisCluster.set("jedisClustername", "jedisClusterwlan"));
System.out.println(jedisCluster.set("jedisClustersex", "男"));
System.out.println(jedisCluster.get("jedisClustername"));
jedisCluster.close();
二、spring整合redis集群
程序启动时,将数据缓存到redis中,如果修改操作再将缓存中的数据更新。针对一些不经常修改但是高访问率的数据进行缓存来减少关系型数据库的压力。
1、redis.xml配置文件中
//redis线程池的配置
//redis集群的配置
192.168.90.124:7001
192.168.90.124:7002
192.168.90.124:7003
192.168.90.124:7004
192.168.90.124:7005
192.168.90.124:7006
//redis集群的连接工厂
或者单个redis的连接工厂配置
//redis操作模板
RedisTemplate源码中有以下几个对象
//RedisTemplate中封装了操作对象,有如下几个:
private ValueOperations valueOps;
private ListOperations listOps;
private SetOperations setOps;
private ZSetOperations zSetOps;
private HyperLogLogOperations hllOps;
2. Spring中使用RedisTemplate模板,封装几种类型的操作
//整合redis各种类型操作,在service中注入该对象,并调用响应的操作
@Service("redisService")
public class RedisService {
@Autowired //注入RedisTemplate
public RedisTemplateredisTemplate;
public ValueOperations setCacheObject(String key,T value){
ValueOperations operation=redisTemplate.opsForValue();
operation.set(key, value);
return operation;
}
public T getCacheObject(String key){
ValueOperations operation=redisTemplate.opsForValue();
return operation.get(key);
}
}
4. spring redis缓存使用:注解
(1)在redis.xml配置文件中添加
//redis缓存管理器
(2)项目中操作
@CacheConfig(cacheNames="prizeinfo")
@Service(value="springRedisService")
public class SpringRedisServiceImpl implements SpringRedisService{
@Autowired
private PrizeinfoService prizeinfoService;
@Cacheable(key="'id:'+#id")
public Prizeinfo getObject(int id) {
return prizeinfoService.getPrizeinfoById(id);
}
@CachePut(key="'id:'+#o.id")
public int insertObject(Prizeinfo o) {
return prizeinfoService.insertPrizeinfo(o);
}
@CachePut(key="'id:'+#prizeinfo.id")
public int updateObject(Prizeinfo prizeinfo) {
return prizeinfoService.updatePrizeinfo(prizeinfo);
}
@CacheEvict(key="'id:'+#id")
public int deleteObjectById(int id) {
return prizeinfoService.deletePrizeinfoById(id);
}
}