Spring Boot学习笔记08--NoSql之MongoDB&Redis

摘要

看完本文你将掌握如下知识点:

  1. Spring Boot对MongoDB的支持
  2. Spring Boot对Redis的支持

SpringBoot系列Spring Boot学习笔记

Spring Boot对MongoDB的支持

pom中加入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

自定义Repository需要继承于MongoRepository,与JPA类似,同样支持命名方法和@Query接口查询。

按方法名进行查询,规则与JPA一致,@Query接口查询就是mongo的原生查询语句的语法类似。

public interface PersonRepository extends MongoRepository<Person, String> {

    //等于
    List<Person> findByName(String name);

    //And --- 等价于 SQL 中的 and 关键字;
    List<Person> findByNameAndAge(String name, Integer age);

    // Or --- 等价于 SQL 中的 or 关键字;
    List<Person> findByNameOrAge(String name, Integer age);
    
    //分页
    Page<Person> findByNameNot(String name, Pageable pageable);

    //mongo原生查询语句
    //等于
    @Query("{'age':?0}")
    List<Person> withQueryFindByAge(Integer age);

    //大于
    @Query("{'age': {'$gt' : ?0}}")
    List<Person> findByAgeGreaterThan(int age);

    //正则匹配name,age范围
    @Query("{ 'name':{'$regex':?0,'$options':'i'}, 'age': {'$gte':?1,'$lte':?2}}")
    public Page<Person> findByNameAndAgeRange(String name,int ageFrom,int ageTo,Pageable page);

    //正则匹配name,age范围,查询结果只封装name和age,当然默认ID是必须封装的
    @Query(value = "{ 'name':{'$regex':?0,'$options':'i'}, 'age': {'$gte':?1,'$lte':?2}}",fields = "{ 'name' : 1, 'age' : 1}")
    public Page<Person> findByNameAndAgeRangeShow(String name,int ageFrom,int ageTo,Pageable page);
}

关于Mongo原生语句的说明可以参考:http://www.cnblogs.com/egger/archive/2013/06/14/3135847.html

如果希望接管spring boot对mongo的自动配置,可以创建如下配置类,这样我们也可以像前文介绍的JPA绑定多数据源那样,绑定多个mongo数据源。

package com.example.mongo;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.ServerAddress;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@Configuration
@EnableMongoRepositories(basePackages = {"com.example.mongo.dao"},mongoTemplateRef = "mongoTemplate")
public class MongoConfig {

    @Value("${spring.data.mongodb.host}")
    String mongoHost;
    @Value("${spring.data.mongodb.uri}")
    String mongoUrl;

    @Bean
    public MongoClient mongoClient() {
        MongoClient mongoClient = new MongoClient(new ServerAddress(mongoHost));
        return mongoClient;
    }

    @Bean
    public MongoDbFactory mongoDbFactory(){
        String database = new MongoClientURI(mongoUrl).getDatabase();
        return new SimpleMongoDbFactory(mongoClient(),database);
    }

    @Bean(name = "mongoTemplate")
    public MongoTemplate mongoTemplate(){
        return new MongoTemplate(mongoDbFactory());
    }
}

Spring Boot对Redis的支持

pom中加入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

然后就可以通过@Autowired注解注入RedisTemplate,比如:

package com.example.redis.dao;

import com.example.redis.domain.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

@Repository
public class StudentDao {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedisTemplate<Object,Object> redisTemplate;

    @Resource(name = "stringRedisTemplate")
    ValueOperations<String,String> valueOperationsStr;

    @Resource(name = "redisTemplate")
    ValueOperations<Object,Object> valueOperations;

    public void setString(String key,String value){
        valueOperationsStr.set(key,value);
    }

    public String getString(String key){
        return valueOperationsStr.get(key);
    }

    public void saveStudent(Student student){
        valueOperations.set(student.getId(),student);
    }

    public Student getStudent(String id){
        return (Student)valueOperations.get(id);
    }
}

同样,如果希望接管spring boot对redis的自动配置,可以创建如下自动配置类:

package com.example.redis;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Value("${spring.redis.database}")
    String redisDatabase;
    @Value("${spring.redis.host}")
    String redisHost;

    @Bean
    public JedisConnectionFactory connectionFactory(){
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
        jedisConnectionFactory.setDatabase(Integer.valueOf(redisDatabase));
        jedisConnectionFactory.setHostName(redisHost);
        return jedisConnectionFactory;
    }


    @Bean
    public Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer() {
        ObjectMapper objectMapper = new ObjectMapper();
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(
                Object.class);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        return jackson2JsonRedisSerializer;
    }

    //用于对存储内容转换为json格式
    @Bean(name = "redisTemplate")
    public RedisTemplate<Object, Object> objRedisTemplate(JedisConnectionFactory connectionFactory,
                                                   Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
        redisTemplate.setConnectionFactory(connectionFactory);
        redisTemplate.setDefaultSerializer(jackson2JsonRedisSerializer);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        return redisTemplate;
    }

    @Bean(name = "stringRedisTemplate")
    public StringRedisTemplate stringRedisTemplate(JedisConnectionFactory connectionFactory) {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(connectionFactory);
        return stringRedisTemplate;
    }
}

本文示例代码下载地址:https://github.com/hanqunfeng/SpringBootStudy

    原文作者:飘逸峰
    原文地址: https://www.jianshu.com/p/ef6f0abbf9b9
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞