springboot使用MongoTemplate绑定多数据源(并且插入时去掉_class)

开门见山,直接上码

1、pom.xml

<!-- 访问mongoDb依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

<!-- 其它配置省略,用springboot标准配置即可 -->

2、application.yml

server:
    port: 8080
spring:
  data:
    mongodb:
      primary:
        uri: mongodb://root:123456@127.0.0.1:27017/users
      secondary:
        uri: mongodb://root:123456@127.0.0.1:27017/logs

3、创建配置文件MongoConfig.java



import com.mongodb.MongoClientURI;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
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.core.convert.*;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

@Configuration
public class MongoConfig {

    @Bean
    @Primary
    @ConfigurationProperties(prefix="spring.data.mongodb.primary")
    public MongoProperties primaryMongoProperties() {
        return new MongoProperties();
    }

    @Primary
    @Bean(name = "mongoTemplate")
    public MongoTemplate primaryMongoTemplate() throws Exception {
        MongoDbFactory factory = primaryFactory(primaryMongoProperties());

        DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
        MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, new MongoMappingContext());
        converter.setTypeMapper(new DefaultMongoTypeMapper(null));//不插入_class

        return new MongoTemplate(factory, converter);
    }


    @Primary
    @Bean(name="primaryFactory")
    public MongoDbFactory primaryFactory(MongoProperties mongoProperties) throws Exception {
        return new SimpleMongoDbFactory(new MongoClientURI(primaryMongoProperties().getUri()));
    }


    @Bean
    @ConfigurationProperties(prefix="spring.data.mongodb.secondary")
    public MongoProperties secondaryMongoProperties() {
        return new MongoProperties();
    }

    @Bean(name = "logTemplate")
    public MongoTemplate secondaryMongoTemplate() throws Exception {
        MongoDbFactory factory = secondaryFactory(secondaryMongoProperties());

        DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
        MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, new MongoMappingContext());
        converter.setTypeMapper(new DefaultMongoTypeMapper(null));//不插入_class

        return new MongoTemplate(factory, converter);
    }

    @Bean
    public MongoDbFactory secondaryFactory(MongoProperties mongoProperties) throws Exception {
        return new SimpleMongoDbFactory(new MongoClientURI(secondaryMongoProperties().getUri()));
    }

    //这个在多数据源时不起作用
//    @Bean(name = "mongoConverter")
//    public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory, MongoMappingContext context, BeanFactory beanFactory) {
//        DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
//        MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context);
//        try {
//            mappingConverter.setCustomConversions(beanFactory.getBean(CustomConversions.class));
//        } catch (NoSuchBeanDefinitionException ignore) {
//        }
//
//        // Don't save _class to mongo 插入时不插入_class
//        mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));
//
//        return mappingConverter;
//    }


}

说明:

加上@Primary表示这是主数据源,默认情况下都会连这个数据源
@Bean(name = "mongoTemplate") 表示把主数据源的名称命名为mongoTemplate,下次直接注入就能引用
MongoDbFactory factory = primaryFactory(primaryMongoProperties());
DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, new MongoMappingContext());
converter.setTypeMapper(new DefaultMongoTypeMapper(null));//不插入_class

上面的代码是为了插入时不插入_class

3、写一个demo类


import com.alibaba.fastjson.JSONObject;
import com.test.common.util.ResultJSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping(value="/api")
public class DemoController {

	@Autowired
	private MongoTemplate mongoTemplate;//第一数据源

	@Autowired
	@Qualifier("logTemplate") //一定要加这个
	private MongoTemplate logTemplate;//日志的访问,第二数据源
	
	
	@ApiOperation(value = "get", notes = "")
	@GetMapping("/demo/get")
	public ResultJSONObject login(HttpServletRequest request) throws Exception {

		BasicQuery basicQuery = new BasicQuery("{_id:'5fe15d86fe7607306c4b13a0'}");
		Map users= mongoTemplate.findOne(basicQuery, Map.class, "users"); //users是第一数据源其中一个集合名称

		BasicQuery basicQuery2 = new BasicQuery("{_id:'5ffeb66008ac0f3b58969ae1'}");
		Map sms_log= logTemplate.findOne(basicQuery2, Map.class, "sms_log"); //sms_log是第二数据源其中一个集合名称

		JSONObject json = new JSONObject();
		json.put("user", users);
		json.put("sms_log", sms_log);
		return ResultJSONObject.success(json);
	}

}


import java.util.List;

import com.fasterxml.jackson.annotation.JsonIgnore;

public class ResultJSONObject {


	private String status;		//状态码
	private String message;		//状态信息
	private Object data;		//返回数据
	
	public ResultJSONObject(String status, String message, Object data) {
		super();
		this.status = status;
		this.message = message;
		this.data = data;
	}
	
	/**
	 * 	状态码为200则表示成功,否则是不成功
	 * @return
	 */
	@JsonIgnore
	public Boolean isSuccess() {
		if("200".equals(this.getStatus())) {
			return true;
		}
		else {
			return false;
		}
	}
	
	@JsonIgnore
	public Boolean isNoFound() {
		if("404".equals(this.getStatus())) {
			return true;
		}
		else {
			return false;
		}
	}
	
	/**
	 * 成功
	 * @param object
	 * @return
	 */
	public static ResultJSONObject success(Object object) {
		String msg = "ok";
		if(null != object) {
			if(object instanceof String) {
				msg = (String) object;
			}
		}
		return new ResultJSONObject("200", msg, object);
	}
	
	/**
	 * 成功
	 * @param object
	 * @return
	 */
	public static ResultJSONObject success(String message, Object object) {
		return new ResultJSONObject("200", message, object);
	}
	
	/**
	 * 服务器异常
	 * @param e
	 * @return
	 */
	public static ResultJSONObject Exception(Object e) {
		String msg = "Exception";
		if(null != e) {
			if(e instanceof String) {
				msg = (String) e;
			}
		}
		return new ResultJSONObject("500", msg, e);
	}
	
	
	/**
	 * 服务器异常
	 * @param e
	 * @return
	 */
	public static ResultJSONObject Exception(String message, Object e) {
		return new ResultJSONObject("500", message, e);
	}
	
	/**
	 * 找不到资源
	 * @return
	 */
	public static ResultJSONObject noFound() {
		return new ResultJSONObject("404", "noFound", null);
	}
	
	/**
	 * 找不到资源
	 * @return
	 */
	public static ResultJSONObject noFound(String message, Object e) {
		return new ResultJSONObject("404", message, e);
	}
	
	/**
	 *	服务器拒绝执行此请求
	 * @param message
	 * @param e
	 * @return
	 */
	public static ResultJSONObject forbidden(String message, Object e) {
		return new ResultJSONObject("403", message, e);
	}
	
	/**
	 * 客户端产生的错误
	 * @return
	 */
	public static ResultJSONObject preconditionFailed(String message, Object object) {
		if(null == message || message.equals("")) {
			message = "preconditionFailed";
		}
		return new ResultJSONObject("412", message, object);
	}
	
	
	/**
	 * 没有权限,401
	 * @return
	 */
	public static ResultJSONObject noAuth(String message, Object object) {
		if(null == message || message.equals("")) {
			message = "noAuth";
		}
		return new ResultJSONObject("401", message, object);
	}
	
	
	public ResultJSONObject() {
		super();
	}

	/**
	 * 200(ok)
	 * 500(Exception)
	 * 404(Exception)
	 */
	public String getStatus() {
		return status;
	}

	/**
	 * 200(ok)
	 * 500(Exception)
	 * 404(Exception)
	 */
	public void setStatus(String status) {
		this.status = status;
	}

	/**
	 * ok(200)
	 * Exception(404、500)
	 */
	public String getMessage() {
		return message;
	}

	/**
	 * ok(200)
	 * Exception(404、500)
	 */
	public void setMessage(String message) {
		this.message = message;
	}

	/**
	 * 自定义的数据返回
	 * @return
	 */
	public Object getData() {
		return data;
	}

	/**
	 * 自定义的数据返回
	 * @param data
	 */
	public void setData(Object data) {
		this.data = data;
	}


	
}

4、返回结果

{
    "status": "200",
    "message": "ok",
    "data": {
        "sms_log": {
            "_id": "5ffeb66008ac0f3b58969ae1",
            "create_time": "2021-01-13 16:59:11",
            "type": 1,
            "reason": "操作成功",
            "error_code": 0
        },
        "user": {
            "_id": "5fe15d86fe7607306c4b13a0",
            "age": "10",
            "type": "1",
            "name": "demo",
        }
    }
}

可以看到,两个数据源都能被访问到

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值