redis配置和yml,properties访问

sunzxh 2019-12-07

配置两个bean:

JedisConnectionFactory 和 RedisTemplate
JedisConnectionFactory factory = new JedisConnectionFactory();//redisSentinelConfiguration()
try {
    Yaml yaml = new Yaml();
    InputStream resourceAsStream = SMSUtil.class.getClassLoader().getResourceAsStream("application.yml");
    JSONObject redisObj = JSONObject.parseObject(JSONObject.toJSONString( yaml.load(resourceAsStream))).getJSONObject("spring").getJSONObject("redis");
    factory.setHostName(redisObj.getString("host"));
    factory.setPort(redisObj.getInteger("port"));
    factory.setPassword(redisObj.getString("password"));
} catch (Exception e) {
    e.printStackTrace();
    System.out.println(e.getMessage());
}
//StringRedisTemplate的构造方法中默认设置了stringSerializer


redisTemplate = new RedisTemplate<>();
//设置开启事务
redisTemplate.setEnableTransactionSupport(true);
//set key serializer
RedisSerializer<String> stringSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringSerializer);
redisTemplate.setValueSerializer(stringSerializer);
redisTemplate.setHashKeySerializer(stringSerializer);
redisTemplate.setHashValueSerializer(stringSerializer);
redisTemplate.setConnectionFactory(factory);
redisTemplate.afterPropertiesSet();

1.java读取yml

Yaml yaml = new Yaml();
InputStream resourceAsStream = SMSUtil.class.getClassLoader().getResourceAsStream("config/commom.yml");
JSONObject redisObj = JSONObject.parseObject(JSONObject.toJSONString(yaml.load(resourceAsStream)));

2.java读取properties:https://www.cnblogs.com/sebastian-tyd/p/7895182.html

properties.getProperty(String key);
//config为属性文件名,放在包com.test.config下,如果是放在src下,直接用config即可  
ResourceBundle resource = ResourceBundle.getBundle("com/test/config/config");
String key = resource.getString("keyWord");

相关推荐

fly00love / 0评论 2020-05-31