You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

79 lines
2.7 KiB

package com.spring.modules.sys.task;
import com.alibaba.fastjson.JSONArray;
import com.spring.common.utils.LdapReadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
/**
* 定时同步域控账号信息到 Redis
*/
@Component
@EnableScheduling
public class LdapAccountRefreshTask {
private static final Logger logger = LoggerFactory.getLogger(LdapAccountRefreshTask.class);
@Value("${spring.ldap.urls}")
private String ldapUrl;
@Value("${spring.ldap.base}")
private String ldapBase;
@Value("${spring.ldap.username}")
private String ldapUserDn;
@Value("${spring.ldap.password}")
private String ldapPassword;
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Scheduled(cron = "${task.data.refreshLdapAccountToRedis}")
public void refreshLdapAccountToRedis() throws NamingException {
//首先查询域控账号的所有数据
Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, ldapUrl);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, ldapUserDn);
env.put(Context.SECURITY_CREDENTIALS, ldapPassword);
env.put(Context.REFERRAL, "ignore");
LdapContext ctx = null;
//尝试解析数据
try{
// 创建DirContext对象,建立与LDAP服务器的连接
ctx = new InitialLdapContext(env, null);
//调用方法读取数据
Map<String, String> ldapAccountMap = LdapReadUtils.getAllLdapAccount(ctx, ldapBase, redisTemplate);
logger.info("域控账号缓存的数量:"+ldapAccountMap.size());
// 数据放到redis中去
// redisTemplate.opsForHash().putAll("ldapAccount", ldapAccountMap);
logger.info("域控账号缓存:"+ JSONArray.toJSONString(ldapAccountMap));
} catch (NamingException | IOException e) {
logger.error("Failed to connect to the LDAP server.");
} finally{
if (null != ctx){
ctx.close();
}
}
}
}