spring @Configuration bean 参数注入

假装没事ソ 提交于 2020-03-05 22:19:15

Spring @Value 设置默认值

Spring 3 supports ${my.server.port:defaultValue} syntax.

@Value("${zookeeper.enable:false}")
private boolean isZkEnable;

添加redis.properties文件

    spring.redis.cluster.nodes=10.48.193.201:7389,10.48.193.201:7388

    spring.redis.cluster.timeout=2000

    spring.redis.cluster.max-redirects=8

编写初始化JedisConnectionFactory连接工厂的java类

    @Configuration

    public class MonitorConfig {

       @Value("${spring.redis.cluster.nodes}")

       private String clusterNodes;

       @Value("${spring.redis.cluster.timeout}")

       private Long timeout;

      @Value("${spring.redis.cluster.max-redirects}")

       private int redirects;

       @Bean

       public RedisClusterConfiguration getClusterConfiguration() {

            Map<String, Object> source = new HashMap<String, Object>();

            source.put("spring.redis.cluster.nodes", clusterNodes);

            source.put("spring.redis.cluster.timeout", timeout);

            source.put("spring.redis.cluster.max-redirects", redirects);

           return new RedisClusterConfiguration(new MapPropertySource("RedisClusterConfiguration", source));

          }

       @Bean

       public JedisConnectionFactory getConnectionFactory() {

           return new JedisConnectionFactory(getClusterConfiguration());

          }

      @Bean

       public JedisClusterConnection getJedisClusterConnection() {

           return (JedisClusterConnection) getConnectionFactory().getConnection();

          }

       @Bean

       public RedisTemplate getRedisTemplate() {

           RedisTemplate clusterTemplate = new RedisTemplate();

           clusterTemplate.setConnectionFactory(getConnectionFactory());

           clusterTemplate.setKeySerializer(new DefaultKeySerializer());

           clusterTemplate.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());

           return clusterTemplate;

          }

       }

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!