一、编辑properties文件
redis.clusters=192.168.126.174:7000,192.168.126.174:7001,192.168.126.174:7002,192.168.126.174:7003,192.168.126.174:7004,192.168.126.174:7005
二、编辑Redis的配置类
@Configuration
@PropertySource("classpath:/properties/redis.properties")
public class RedisConfig {
/**
* SpringBoot整合Redis集群
*/
@Value("${redis.clusters}")
private String jedisClusters;
@Bean
@Scope("prototype")
public JedisCluster jedisCluster() {
Set<HostAndPort> setNodes = new HashSet<>();
String[] nodes = jedisClusters.split(",");
for (String node : nodes) {
String host = node.split(":")[0];
Integer port = Integer.parseInt(node.split(":")[1]);
HostAndPort hostAndPort = new HostAndPort(host, port);
setNodes.add(hostAndPort);
}
return new JedisCluster(setNodes);
}
}
三、封装Mapper工具API
public class ObjectMapperUtil {
private static final ObjectMapper MAPPER = new ObjectMapper();
public static String toJSON(Object obj) {
String result = null;
try {
result = MAPPER.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return result;
}
public static <T> T toObj(String json, Class<T> targetClass) {
T t = null;
try {
t=MAPPER.readValue(json,targetClass);
} catch (JsonProcessingException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return t;
}
}
四、自定义注解
@Target(ElementType.METHOD)//注解对谁有效
@Retention(RetentionPolicy.RUNTIME)//运行时有效
public @interface CacheFind {
String key() default "";//如果用户设定参数,则使用用户的,如果用户没有设定参数,就使用自动生成
int seconds() default 0;
//int seconds() default 0;//默认值为0
}
五、编辑CacheAOP
@Component //将对象交给spring容器管理
@Aspect //自定义切面
public class CacheAOP {
@Autowired
private JedisCluster jedis;
@Around("@annotation(cacheFind)")
public Object around(ProceedingJoinPoint joinPoint, CacheFind cacheFind) {
//调用方法,获取key
String key = getKey(joinPoint, cacheFind);
String value = jedis.get(key);
Object object = null;
try {
if (StringUtils.isEmpty(value)) {
//缓存中没有数据,查询数据库
object = joinPoint.proceed();
String json = ObjectMapperUtil.toJSON(object);
//判断是否需要超时设定
if (cacheFind.seconds() > 0) {
jedis.setex(key, cacheFind.seconds(), json);
} else {
//该数据永不超时
jedis.set(key, json);
}
System.out.println("AOP查询数据库!!!");
} else {
//需要动态的获取返回值类型
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Class<?> targetClass = methodSignature.getReturnType();
object = ObjectMapperUtil.toObj(value, targetClass);
System.out.println("AOP查询缓存!!!");
}
} catch (Throwable e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return object;
}
//动态获取key
private String getKey(ProceedingJoinPoint joinPoint, CacheFind cacheFind) {
//1.检查用户是否传递key
String key = cacheFind.key();
if (StringUtils.isEmpty(key)) {
//包名.类名.方法名::第一个参数
String className = joinPoint.getSignature().getDeclaringTypeName();
String mothedName = joinPoint.getSignature().getName();
Object arg0 = joinPoint.getArgs()[0];
key = className + "." + mothedName + "::" + arg0;
}
return key;
}
}
关于redis集群报错说明
上述报错信息表示没有可用的redis节点.排查步骤如下: