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

4 months ago
4 months ago
4 months ago
4 months ago
4 months ago
4 months ago
  1. package com.spring.modules.sys.task;
  2. import com.alibaba.fastjson.JSONArray;
  3. import com.spring.common.utils.LdapReadUtils;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.beans.factory.annotation.Value;
  8. import org.springframework.data.redis.core.RedisTemplate;
  9. import org.springframework.scheduling.annotation.EnableScheduling;
  10. import org.springframework.scheduling.annotation.Scheduled;
  11. import org.springframework.stereotype.Component;
  12. import javax.naming.Context;
  13. import javax.naming.NamingException;
  14. import javax.naming.ldap.InitialLdapContext;
  15. import javax.naming.ldap.LdapContext;
  16. import java.io.IOException;
  17. import java.util.Map;
  18. import java.util.Properties;
  19. /**
  20. * 定时同步域控账号信息到 Redis
  21. */
  22. @Component
  23. @EnableScheduling
  24. public class LdapAccountRefreshTask {
  25. private static final Logger logger = LoggerFactory.getLogger(LdapAccountRefreshTask.class);
  26. @Value("${spring.ldap.urls}")
  27. private String ldapUrl;
  28. @Value("${spring.ldap.base}")
  29. private String ldapBase;
  30. @Value("${spring.ldap.username}")
  31. private String ldapUserDn;
  32. @Value("${spring.ldap.password}")
  33. private String ldapPassword;
  34. @Autowired
  35. private RedisTemplate<String, Object> redisTemplate;
  36. @Scheduled(cron = "${task.data.refreshLdapAccountToRedis}")
  37. public void refreshLdapAccountToRedis() throws NamingException {
  38. //首先查询域控账号的所有数据
  39. Properties env = new Properties();
  40. env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
  41. env.put(Context.PROVIDER_URL, ldapUrl);
  42. env.put(Context.SECURITY_AUTHENTICATION, "simple");
  43. env.put(Context.SECURITY_PRINCIPAL, ldapUserDn);
  44. env.put(Context.SECURITY_CREDENTIALS, ldapPassword);
  45. env.put(Context.REFERRAL, "ignore");
  46. LdapContext ctx = null;
  47. //尝试解析数据
  48. try{
  49. // 创建DirContext对象,建立与LDAP服务器的连接
  50. ctx = new InitialLdapContext(env, null);
  51. //调用方法读取数据
  52. Map<String, String> ldapAccountMap = LdapReadUtils.getAllLdapAccount(ctx, ldapBase, redisTemplate);
  53. logger.info("域控账号缓存的数量:"+ldapAccountMap.size());
  54. // 数据放到redis中去
  55. // redisTemplate.opsForHash().putAll("ldapAccount", ldapAccountMap);
  56. logger.info("域控账号缓存:"+ JSONArray.toJSONString(ldapAccountMap));
  57. } catch (NamingException | IOException e) {
  58. logger.error("Failed to connect to the LDAP server.");
  59. } finally{
  60. if (null != ctx){
  61. ctx.close();
  62. }
  63. }
  64. }
  65. }