1.主配置文件application.properties
spring.redis.database = 4 spring.redis.host =192.168.31.97 spring.redis.password = foobared spring.redis.port = 6379 spring.redis.timeout = 2000
因为使用的还是springboot框架,所以和java的配置完全一样
2.配置注入实例
@Configuration class RedisConf (val jedisConnFactory: JedisConnectionFactory) { @Bean(name = Array("objectTemplate")) def objectTemplate[T]: RedisTemplate[String, T] = { val template = new RedisTemplate[String, T] template.setConnectionFactory(jedisConnFactory) template.setKeySerializer(new StringRedisSerializer) template.setValueSerializer(new JdkSerializationRedisSerializer) template } }
3.使用
@Component class MyRedis(@Autowired@Qualifier("objectTemplate") private val objectTemplate:RedisTemplate[String, String]) { def setValue(key:String , value:String): Unit = { objectTemplate.opsForValue().set(key , value) } def getValue(key:String):String={ objectTemplate.opsForValue().get(key) } }
4.测试
@Test def testSetValue() = { useRedis.setValue("key" , "hello world") }
@Test def testGetValue() = { println(s"value is ${useRedis.getValue("key")}") }
最终打印
value is hello world