一 集成Redis单机版
1 pom文件添加jar
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2 在配置文件application.properties添加redis配置
# 配置redis
spring.redis.host=192.168.32.130
spring.redis.port=6379
spring.redis.database=1
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=500
spring.redis.pool.min-idle=0
spring.redis.timeout=0
3 新建redisService.java类,代码如下
package com.gog.redis.service;
public interface RedisService {
public void set(String key, Object value);
public Object get(String key);
}
4 增加实现类redisServiceImpl.java
package com.gog.redis.service.impl;
import javax.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import com.gog.redis.service.RedisService;
@Service
public class RedisServiceImpl implements RedisService {
@Resource
private RedisTemplate<String,Object> redisTemplate;
public void set(String key, Object value) {
ValueOperations<String,Object> vo = redisTemplate.opsForValue();
vo.set(key, value);
}
public Object get(String key) {
ValueOperations<String,Object> vo = redisTemplate.opsForValue();
return vo.get(key);
}
}
至此,集成完毕,可直接调用方法实现
二 集群版配置
1 配置文件增加如下配置
#整合redis集群
spring.redis.cluster.nodes=192.168.66.66:7001,192.168.66.66:7002,192.168.66.66:7003,192.168.66.66:7004
2 编写ReidsConfig.java工具类
package com.gog.config;
import java.util.HashSet;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
@Configuration //applicationContext.xml 类似于创建这样一个配置文件
public class RedisConfig {
//注入集群节点信息
@Value("${spring.redis.cluster.nodes}")
private String clusterNodes;
@Bean
public JedisCluster getJedisCluster(){
//分割集群节点
String[] cNodes = clusterNodes.split(",");
//创建set集合对象
Set<HostAndPort> nodes = new HashSet<>();
//循环集群节点对象
for (String node : cNodes) {
String[] hp = node.split(":");
nodes.add(new HostAndPort(hp[0], Integer.parseInt(hp[1])));
}
JedisCluster jedisCluster = new JedisCluster(nodes);
return jedisCluster;
}
}
3 使用方式
在类中注入
@Autowired
private JedisCluster jedisCluster;
至此,集成redis也搭建完毕!!1