import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@Service
public class RedisUtil {
@Autowired
RedisTemplate redisTemplate;
public T getObject(String key, Class clazz) {
Object valueObj = redisTemplate.opsForValue().get(key);
if (valueObj == null) {
return null;
}
if (clazz.isInstance(valueObj)) {
return (T) valueObj;
} else if (clazz == Long.class && valueObj instanceof Integer) {
Integer obj = (Integer) valueObj;
return (T) Long.valueOf(obj.longValue());
}
return null;
}
public void setObject(String key, Object value, Long second) {
redisTemplate.opsForValue().set(key, value, second, TimeUnit.SECONDS);
}
public void setObjectForever(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
public Long increment(String key, Long second) {
Long value = redisTemplate.opsForValue().increment(key);
redisTemplate.expire(key, second, TimeUnit.SECONDS);
return value;
}
public void decrement(String key) {
redisTemplate.opsForValue().decrement(key);
}
public boolean setIfAbsent(String key, Long second) {
return redisTemplate.opsForValue().setIfAbsent(key, "1", second, TimeUnit.SECONDS);
}
}
import cn.hutool.core.date.DateUtil;
import com.easy.hotel.pms.service.impl.RedisUtil;
import lombok.AllArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
@AllArgsConstructor
public class RedisGeoCommunityRunner {
private final RedisUtil redisUtil;
private static String redisGeoCommunityCount = "REDIS_GEO_COMMUNITY_COUNT";
@Scheduled(cron = "*/5 * * * * ?")//每隔5秒执行一次
public void totalIndex() {
try {
System.out.println(com.easy.hotel.pms.util.DateUtil.toDateTimeStr(DateUtil.toLocalDateTime(new Date())) );
Integer count = redisUtil.getObject(redisGeoCommunityCount, Integer.class);
if(count == null){
redisUtil.setObjectForever(redisGeoCommunityCount,1);
count = redisUtil.getObject(redisGeoCommunityCount, Integer.class);
}
if(count > 1){
return ;
}else{
redisUtil.setObjectForever(redisGeoCommunityCount,2);
}
execteOnlyOnce( );
} catch (Exception e) {
e.printStackTrace();
}
}
private void execteOnlyOnce( ) {
System.out.println("只执行一次");
}
}