redis配置和yml,properties访问

Posted 天天大傻猫

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了redis配置和yml,properties访问相关的知识,希望对你有一定的参考价值。

配置两个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"); 

 

 

 

 

 

 

 

 

 

 

 

 

以上是关于redis配置和yml,properties访问的主要内容,如果未能解决你的问题,请参考以下文章

单体Spring boot引入外部配置文件yml,properties

为啥springboot中使用redis不配置会报错

springboot加载properties和yml配置文件的顺序

application.yml和application.properties文件的区别

SpringBoot中.yml和.application的区别以及.yml和.properties配置在线转换

一目了然之SpringBoot中yml和properties配置文件