Как реализовать мультитенантность для redis при весенней загрузке - PullRequest
0 голосов
/ 09 января 2020

Я работаю над тем, чтобы сделать все приложение мультитенантным, но зависшим на Redis. Пока что я создал карту JedisConnectionFactory и попытался передать ее в RedisTemplate, но она выдает java.lang.IllegalArgumentException: template not initialized; call afterPropertiesSet() before using it.

Ниже приведены фрагменты кода:

@Component
public class RedisConfiguration {

    @Autowired
    private DSConfig dsConfig;

    private Map<String,JedisConnectionFactory> jedisConnectionFactoryMap = new HashMap<>();

    private static Logger LOGGER = LoggerFactory.getLogger(RedisConfiguration.class);

    @PostConstruct
    public void initializeJedisConnectionFactories() {

        for(DatasourceDetail datasourceDetail : dsConfig.getDatasources()) {
            RedisStandaloneConfiguration redisConfig = new RedisStandaloneConfiguration();
            redisConfig.setHostName(datasourceDetail.getRedisHost());
            redisConfig.setPassword(RedisPassword.of(datasourceDetail.getRedisPassword()));
            redisConfig.setPort(Integer.parseInt(datasourceDetail.getRedisPort()));
            JedisClientConfiguration configuration = JedisClientConfiguration.builder().usePooling().
                    poolConfig(new JedisPoolConfig()).build();
            jedisConnectionFactoryMap.put(datasourceDetail.getTenantId()
                    ,new JedisConnectionFactory(redisConfig,configuration));
        }
        LOGGER.info("Connection factory count " + jedisConnectionFactoryMap.size());
    }

    public RedisTemplate< String, Object > redisTemplate() throws Exception {
        final RedisTemplate< String, Object > template =  new RedisTemplate< String, Object >();
        template.setConnectionFactory( jedisConnectionFactory() );
        template.setKeySerializer( new StringRedisSerializer() );
        template.setHashValueSerializer( new GenericToStringSerializer< Object >( Object.class ) );
        template.setValueSerializer( new GenericToStringSerializer< Object >( Object.class ) );
        return template;
    }

    JedisConnectionFactory jedisConnectionFactory() throws Exception {
        if(TenantContext.getCurrentTenant()==null) {
            throw new Exception("No tenant context found");
        }
        LOGGER.info("Returning redis connection for tenant" + TenantContext.getCurrentTenant());
        return jedisConnectionFactoryMap.get(TenantContext.getCurrentTenant());
    }
}

И я использую шаблон redis, как показано ниже:

@CrossOrigin("*")
@RestController
@RequestMapping("/redis")
public class RedisController {

    @Autowired
    private RedisConfiguration redisConfiguration;


    @GetMapping("/set")
    @ResponseBody
    public Object set(@RequestParam(value = "key", required = true) String key,
                      @RequestParam(value = "value", required = true) String value) throws Exception {
        redisConfiguration.redisTemplate().opsForValue().set( key,value );
        return true;
    }

    @GetMapping("/get")
    @ResponseBody
    public Object get(@RequestParam(value = "key", required = true) String key) throws Exception {
        redisConfiguration.redisTemplate().opsForValue().get(key);
        return true;
    }
}

В любом случае, я могу реализовать это лучше или есть какой-то другой способ, который обеспечивает Spring Redis?

1 Ответ

0 голосов
/ 10 января 2020

Наконец-то мне удалось решить, явно вызвав afterPropertiesSet ().

...