遵守“约定大于配置”原则的Spring boot集成常用的NO SQL是很方便的,本例拿redis做一个简单的demo,使用Redis的set和get命令。
引入redis的依赖包。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
在@Configuration或者集成了这个注解的注解标识的类中声明一个Redis的bean,本例是在入口类上声明的Bean:
@SpringBootApplication
public class Application {
@Bean
StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
return new StringRedisTemplate(connectionFactory);
}
public static void main(String[] args) throws InterruptedException {
SpringApplication.run(Application.class, args);
}
}
在Controller里注入StringRedisTemplate:
@RestController
public class RedisController {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@RequestMapping("/redis/set")
public ResultBean set(@RequestParam(name = "name", defaultValue = "CYF") String name){
stringRedisTemplate.opsForValue().set("test", name);
return ResultBean.ok();
}
@RequestMapping("/redis/get")
public ResultBean set(){
String value = stringRedisTemplate.opsForValue().get("test");
return ResultBean.ok(value);
}
}
启动项目,并访问:
set命令:
get命令:
本例下redis是默认访问的127.0.0.1 6379的redis server,我们可以修改配置让其访问指定的redis server。
到spring boot的官方说明上可以找到对应配置,把这些配置写到resources/appcation.properties这里就不做演示了。
# REDIS (RedisProperties)
spring.redis.cluster.max-redirects= # Maximum number of redirects to follow when executing commands across the cluster.
spring.redis.cluster.nodes= # Comma-separated list of "host:port" pairs to bootstrap from.
spring.redis.database=0 # Database index used by the connection factory.
spring.redis.url= # Connection URL, will override host, port and password (user will be ignored), e.g. redis://user:password@example.com:6379
spring.redis.host=localhost # Redis server host.
spring.redis.password= # Login password of the redis server.
spring.redis.ssl=false # Enable SSL support.
spring.redis.pool.max-active=8 # Max number of connections that can be allocated by the pool at a given time. Use a negative value for no limit.
spring.redis.pool.max-idle=8 # Max number of "idle" connections in the pool. Use a negative value to indicate an unlimited number of idle connections.
spring.redis.pool.max-wait=-1 # Maximum amount of time (in milliseconds) a connection allocation should block before throwing an exception when the pool is exhausted. Use a negative value to block indefinitely.
spring.redis.pool.min-idle=0 # Target for the minimum number of idle connections to maintain in the pool. This setting only has an effect if it is positive.
spring.redis.port=6379 # Redis server port.
spring.redis.sentinel.master= # Name of Redis server.
spring.redis.sentinel.nodes= # Comma-separated list of host:port pairs.
spring.redis.timeout=0 # Connection timeout in milliseconds.
从配置上可以看到,既支持单个redis,也支持redis集群和连接池,还是很强大的,中小型的并发量是可以支持的了。