springboot nosql
1. redis
参考资料:
- https://docs.spring.io/spring-boot/docs/1.4.7.RELEASE/reference/htmlsingle/#boot-features-caching-provider-redis
- https://docs.spring.io/spring-data/data-redis/docs/1.7.6.RELEASE/reference/html/
1.1 引入依赖
引入redis的依赖包,主要基于spring data redis来操作redis,其中包括:
- spring-data-redis
- jedis
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
1.2 连接redis
配置application.properties,连接redis
# REDIS (RedisProperties)
spring.redis.database=0
spring.redis.host=192.168.137.101
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=0
1.3 编码使用
经过上述配置并启动应用后,spring的上下文中就已经装配了
- RedisConnectionFactory,redis 的连接工厂
- StringRedisTemplate,相当于RedisTemplate<String, String>
测试代码
@RestController
@RequestMapping(path="redis")
@Api(tags="redis 测试")
public class RedisController {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@ApiOperation(value="放入值")
@RequestMapping(method=RequestMethod.POST)
public Long set(@RequestParam String key, @RequestParam String value) {
stringRedisTemplate.opsForValue().set(key, value);
return stringRedisTemplate.opsForValue().size(key);
}
@ApiOperation(value="取值")
@RequestMapping(path="/{key}/", method=RequestMethod.GET)
public String get(@PathVariable String key) {
return stringRedisTemplate.opsForValue().get(key);
}
@ApiOperation(value="根据key删除值")
@DeleteMapping(path="/{key}/")
public Boolean del(@PathVariable String key) {
stringRedisTemplate.delete(key);
return Boolean.TRUE;
}
}
1.4 自定义redisTemplate
定义redisTemplate
@Bean
public RedisTemplate<Long, User> userRedisTemplate(RedisConnectionFactory factory) {
RedisTemplate<Long, User> redisTemplate = new RedisTemplate<Long, User>();
redisTemplate.setConnectionFactory(factory);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
om.configure(SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS, false);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
jackson2JsonRedisSerializer.setObjectMapper(om);
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setKeySerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
使用redisTemplate
@RestController
@RequestMapping(path="redis")
@Api(tags="redis 测试")
public class RedisController {
@Autowired
private RedisTemplate<Long, User> userRedisTemplate;
@ApiOperation(value="测试redis放入对象")
@RequestMapping(path="user", method=RequestMethod.POST)
public User setUser(@ModelAttribute User user) {
userRedisTemplate.opsForValue().set(user.getId(), user);
return user;
}
}
2. mongo
参考资料:
- https://docs.spring.io/spring-boot/docs/1.4.7.RELEASE/reference/htmlsingle/#boot-features-mongodb
- https://docs.spring.io/spring-data/data-mongodb/docs/1.9.6.RELEASE/reference/html/
2.1 引入依赖
引入mongodb的依赖包,主要基于spring data mongodb来操作mongodb,其中包括:
- spring-data-mongodb
- mongodb-driver
<!-- mongodb -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2.2 连接mongo
配置application.properties,连接redis
# MONGODB (MongoProperties)
#spring.data.mongodb.authentication-database= # Authentication database name.
#spring.data.mongodb.field-naming-strategy= # Fully qualified name of the FieldNamingStrategy to use.
#spring.data.mongodb.grid-fs-database= # GridFS database name.
#spring.data.mongodb.repositories.enabled=true # Enable Mongo repositories.
# 2.x
spring.data.mongodb.host=192.168.137.101
spring.data.mongodb.port=27017
spring.data.mongodb.database=test
#spring.data.mongodb.username= # Login user of the mongo server.
#spring.data.mongodb.password= # Login password of the mongo server.
# 3.x
#spring.data.mongodb.uri=mongodb://name:pass@192.168.137.101:27017/test
#spring.data.mongodb.uri=mongodb://192.168.137.101:27017/test
2.3 编码使用
经过上述配置并启动应用后,spring的上下文中就已经装配了
- MongoDbFactory,mongo 的连接工厂
- MongoTemplate
测试代码
@RestController
@RequestMapping(path="mongo")
@Api(tags="mongo 测试")
public class MongoController {
@Autowired
private MongoTemplate mongoTemplate;
@ApiOperation(value="增加用户")
@RequestMapping(method=RequestMethod.POST)
public User set(@ModelAttribute User user) {
mongoTemplate.insert(user);
return user;
}
@ApiOperation(value="修改用户年龄")
@RequestMapping(method=RequestMethod.PUT)
@ApiImplicitParams({
@ApiImplicitParam(value="用户id", name="id", required=true, dataType="Integer", paramType="form"),
@ApiImplicitParam(value="年龄", name="age", required=false, dataType="integer", paramType="form")
})
public WriteResult put(@ApiIgnore @ModelAttribute User user) {
// 如果只修改部分字段可以用该方法
Criteria criteria = Criteria.where("id").is(user.getId());
Update update = new Update().set("age", user.getAge());
return mongoTemplate.updateFirst(new Query(criteria), update, User.class);
}
@ApiOperation(value="查询用户")
@RequestMapping(method=RequestMethod.GET)
public List<User> get(@RequestParam(required=false) String name) {
Criteria criteria = Criteria.where("name").regex(name);
return mongoTemplate.find(new Query(criteria), User.class);
}
@ApiOperation(value="根据id查询用户")
@GetMapping(path="/{id}/")
public User findById(@ApiParam(value="用户id") @PathVariable Long id) {
return mongoTemplate.findById(id, User.class);
}
@ApiOperation(value="根据id删除用户")
@DeleteMapping(path="/{id}/")
public Boolean del(@PathVariable String id) {
User user = mongoTemplate.findById(id, User.class);
if(user != null) {
mongoTemplate.remove(user);
}
return Boolean.TRUE;
}
}
3. elasticsearch
参考资料:
- https://docs.spring.io/spring-boot/docs/1.4.7.RELEASE/reference/htmlsingle/#boot-features-elasticsearch
- https://docs.spring.io/spring-data/elasticsearch/docs/2.0.6.RELEASE/reference/html/
- https://github.com/spring-projects/spring-data-elasticsearch
3.1 引入依赖
引入elasticsearch的依赖包,主要基于spring data elasticsearch来操作elasticsearch,其中包括:
- spring-data-elasticsearch
<!-- elasticsearch -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
3.2 连接es
配置application.properties,连接elasticsearch
# JEST (Elasticsearch HTTP client) (JestProperties)
spring.elasticsearch.jest.uris=http://192.168.137.101:9200
spring.elasticsearch.jest.read-timeout=10000
spring.elasticsearch.jest.connection-timeout=3000
spring.elasticsearch.jest.username=elastic
spring.elasticsearch.jest.password=changme
3.3 编码使用
经过上述配置并启动应用后,spring的上下文中就已经装配了
- ElasticsearchTemplate
测试代码
@RestController
@RequestMapping(path="elasticsearch")
@Api(tags="elasticsearch 测试")
public class ElasticController {
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@ApiOperation(value="增加/修改用户")
@RequestMapping(method=RequestMethod.POST)
public User set(@ModelAttribute User user) {
IndexQuery indexQuery = new IndexQueryBuilder()
.withId(String.valueOf(user.getId()))
.withObject(user)
.build();
elasticsearchTemplate.index(indexQuery);
return user;
}
@ApiOperation(value="查询用户(模糊前匹配)")
@RequestMapping(method=RequestMethod.GET)
public List<User> get(@RequestParam(required=false) String name) {
Criteria criteria = Criteria.where("name").startsWith(name);
CriteriaQuery query = new CriteriaQuery(criteria);
return elasticsearchTemplate.queryForList(query, User.class);
}
@ApiOperation(value="根据id查询用户")
@GetMapping(path="/{id}/")
public User findById(@ApiParam(value="用户id") @PathVariable Long id) {
Criteria criteria = Criteria.where("id").is(id);
CriteriaQuery query = new CriteriaQuery(criteria);
return elasticsearchTemplate.queryForObject(query, User.class);
}
@ApiOperation(value="根据id删除用户")
@DeleteMapping(path="/{id}/")
public Boolean del(@PathVariable String id) {
// 方法一:根据id删除
elasticsearchTemplate.delete(User.class, id);
// 方法二:根据条件删除,适合批量删除
// Criteria criteria = Criteria.where("id").is(id);
// CriteriaQuery criteriaQuery = new CriteriaQuery(criteria);
// elasticsearchTemplate.delete(criteriaQuery, User.class);
return Boolean.TRUE;
}
}
4. 备注说明
mongo 和 elasticsearch 也可以不使用 Template(MongoTemplate/ElasticsearchTemplate),可是使用Spring Data Repository 进行数据库的持久化。例如:
4.1 elasticsearch Repository
public interface UserRepository extends CrudRepository<User, Long> {
Long deleteByLastname(String lastname);
List<User> removeByLastname(String lastname);
}
4.2 mongo Repository
public interface PersonRepository extends Repository<User, Long> {
List<Person> findByEmailAddressAndLastname(EmailAddress emailAddress, String lastname);
// Enables the distinct flag for the query
List<Person> findDistinctPeopleByLastnameOrFirstname(String lastname, String firstname);
List<Person> findPeopleDistinctByLastnameOrFirstname(String lastname, String firstname);
// Enabling ignoring case for an individual property
List<Person> findByLastnameIgnoreCase(String lastname);
// Enabling ignoring case for all suitable properties
List<Person> findByLastnameAndFirstnameAllIgnoreCase(String lastname, String firstname);
// Enabling static ORDER BY for a query
List<Person> findByLastnameOrderByFirstnameAsc(String lastname);
List<Person> findByLastnameOrderByFirstnameDesc(String lastname);
}