MongoDB:mongodb在spring项目中的配置
最近在做基于mongodb的spring项目架构,有个问题跟大家分享一下,也方便自己以后能够用到 先看一个简单的项目架构: 在架构方面唯一需要说的是采用的是spring的注解: 下面是部分代码,部分。 /** * @author jessonlv * 用户注册接口 */ @Controller@Request
最近在做基于mongodb的spring项目架构,有个问题跟大家分享一下,也方便自己以后能够用到
先看一个简单的项目架构:
在架构方面唯一需要说的是采用的是spring的注解:
下面是部分代码,部分。
/** * @author jessonlv * 用户注册接口 */ <strong>@Controller @RequestMapping("/user")</strong> public class UserInfoController { @Autowired private UserInfoManager userManager; //接口文档 <strong>@RequestMapping(method=RequestMethod.GET)</strong> public String list(HttpServletRequest request,HttpServletResponse response){ response.setContentType("text/html;charset=utf-8"); return "user"; } //检测用户信息-根据帐户 <strong>@RequestMapping(value="/check",method=RequestMethod.GET) </strong> public String getUser(HttpServletRequest request,HttpServletResponse response) throws Exception{ //设置HTTP头 response.setContentType("text/html;charset=utf-8"); //参数获取 String account=StringUtil.formatStringParameter(request.getParameter("account"), null); String key=StringUtil.formatStringParameter(request.getParameter("key"), null);//验证调用方 //参数有效性验证 if(account==null){ throw new ParameterException(); } //TODO:key验证 //查询对象 BasicDBObject o=new BasicDBObject("account",account); try { //取数据库 DBObject doc=userManager.getUserInfo(o); //输出结果 PrintWriter writer=response.getWriter(); writer.write(doc.toString()); } catch (Exception e) { e.printStackTrace(); //输出结果 PrintWriter writer=response.getWriter(); writer.write(new BasicDBObject().toString()); } //db.find(query).skip(pos).limit(pagesize)分页 return null; }
采用mongodb的最大好处中的其中一个就是不用写bean,只需做一些简单的配置
我们看spring-servlet.xml 的配置内容
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util" xmlns:p="http://www.springframework.org/schema/p" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tool="http://www.springframework.org/schema/tool" xsi:schemaLocation=" http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/tool http://www.springframework.org/schema/tool/spring-tool-3.1.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd" default-autowire="byName" default-lazy-init="true"> <context:annotation-config /> <context:component-scan base-package="com.ishowchina.user" /> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".html" /> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="utf-8" /> <!-- 支持json --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean> </list> </property> </bean> <!-- 导入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:appconfig.properties</value> </list> </property> </bean> <!-- 数据源 --> <bean id="dataSource" class="com.ishowchina.user.dao.DataSource"> <property name="ip" value="localhost"/> <property name="port" value="27017"/> </bean> <bean id="userDao" class="com.ishowchina.user.dao.impl.UserInfoDaoImpl"> <property name="dbName" value="prop"/> <property name="tableName" value="userinfo"/> <property name="dataSource" ref="dataSource"/> </bean> <bean id="stationDao" class="com.ishowchina.user.dao.impl.StationInfoDaoImpl"> <property name="dbName" value="prop"/> <property name="tableName" value="stationinfo"/> <property name="dataSource" ref="dataSource"/> </bean> </beans>
上面的都是些常规的配置,最重要的就是数据源部分
道理其实还是和bean是一样的,这在项目启动的前期都已经映射了。每写一个dao就配置一个
接口的输出结果也很简单:DBObject myDocDbObject = userManager.getUserInfo(repeatAccount);
String str = myDocDbObject.toString(); 是一个json格式的字符。
呵呵,做个小总结,方便忘记了。

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











이 기사는 데비안 시스템에서 MongoDB를 구성하여 자동 확장을 달성하는 방법을 소개합니다. 주요 단계에는 MongoDB 복제 세트 및 디스크 공간 모니터링 설정이 포함됩니다. 1. MongoDB 설치 먼저 MongoDB가 데비안 시스템에 설치되어 있는지 확인하십시오. 다음 명령을 사용하여 설치하십시오. sudoaptupdatesudoaptinstall-imongb-org 2. MongoDB Replica 세트 MongoDB Replica 세트 구성은 자동 용량 확장을 달성하기위한 기초 인 고 가용성 및 데이터 중복성을 보장합니다. MongoDB 서비스 시작 : sudosystemctlstartMongodsudosys

이 기사는 데비안 시스템에서 고도로 사용 가능한 MongoDB 데이터베이스를 구축하는 방법에 대해 설명합니다. 우리는 데이터 보안 및 서비스가 계속 운영되도록하는 여러 가지 방법을 모색 할 것입니다. 주요 전략 : ReplicaSet : ReplicaSet : 복제품을 사용하여 데이터 중복성 및 자동 장애 조치를 달성합니다. 마스터 노드가 실패하면 복제 세트는 서비스의 지속적인 가용성을 보장하기 위해 새 마스터 노드를 자동으로 선택합니다. 데이터 백업 및 복구 : MongoDump 명령을 정기적으로 사용하여 데이터베이스를 백업하고 데이터 손실의 위험을 처리하기 위해 효과적인 복구 전략을 공식화합니다. 모니터링 및 경보 : 모니터링 도구 (예 : Prometheus, Grafana) 배포 MongoDB의 실행 상태를 실시간으로 모니터링하고

프로젝트 요구 사항을 기반으로 최상의 Java 프레임워크를 선택하려면 다음이 필요합니다. 프로젝트 요구 사항 결정(애플리케이션 유형, 사용자 수, 필수 기능, 성능 요구 사항) 사용 가능한 프레임워크 조사(예: Spring, SpringBoot, Hibernate, JakartaEE) 프레임워크 평가(기능 세트, 사용자 커뮤니티, 성능, 지속적인 지원)

해시 값으로 저장되기 때문에 MongoDB 비밀번호를 Navicat을 통해 직접 보는 것은 불가능합니다. 분실 된 비밀번호 검색 방법 : 1. 비밀번호 재설정; 2. 구성 파일 확인 (해시 값이 포함될 수 있음); 3. 코드를 점검하십시오 (암호 하드 코드 메일).

Spring Framework 5.0에는 다음과 같은 새로운 기능이 도입되었습니다. WebFlux 지원: 고성능 웹 애플리케이션 구축을 위한 반응형 프로그래밍에 대한 지원을 제공합니다. 주석 기반 구성: 주석을 사용하여 Bean 및 구성 요소 구성을 단순화합니다. SpringDataReactive 지원: 반응형 데이터베이스 액세스를 확장하여 데이터베이스와의 상호 작용을 단순화합니다. Java 구성의 프로세스 표현식: 구성에서 동적 표현식을 사용할 수 있습니다. 향상된 예외 처리: 처리되지 않은 예외를 적절하게 처리하는 일반적인 메커니즘을 제공합니다.

MongoDB 및 Relational Database : 심층 비교이 기사는 NOSQL 데이터베이스 MongoDB와 전통적인 관계형 데이터베이스 (예 : MySQL 및 SQLServer)의 차이점을 심층적으로 탐구합니다. 관계형 데이터베이스는 행 및 열의 테이블 구조를 사용하여 데이터를 구성하는 반면 MongoDB는 유연한 문서 지향 모델을 사용하여 최신 응용 프로그램의 요구에 더 잘 어울립니다. 주로 데이터 구조를 차별화합니다. 관계형 데이터베이스는 사전 정의 된 스키마 테이블을 사용하여 데이터를 저장하고 기본 키와 외부 키를 통해 테이블 간의 관계가 설정됩니다. MongoDB는 JSON과 같은 BSON 문서를 사용하여 컬렉션에 저장하며 각 문서 구조는 패턴없는 설계를 달성하기 위해 독립적으로 변경할 수 있습니다. 건축 설계 : 관계형 데이터베이스는 사전 정의 된 고정 스키마가 필요합니다. MongoDB는 지원합니다

CentOS 시스템 하에서 MongoDB 효율적인 백업 전략에 대한 자세한 설명이 기사는 CentOS 시스템에서 MongoDB 백업을 구현하기위한 다양한 전략을 자세히 소개하여 데이터 보안 및 비즈니스 연속성을 보장 할 것입니다. Docker 컨테이너 환경에서 수동 백업, 시간이 정해진 백업, 자동 스크립트 백업 및 백업 메소드를 다루고 백업 파일 관리를위한 모범 사례를 제공합니다. 수동 백업 : MongoDump 명령을 사용하여 Manual 전체 백업을 수행하십시오 (예 : Mongodump-HlocalHost : 27017-U username-P password-d 데이터베이스 이름 -o/백업 디렉토리이 명령은 지정된 데이터베이스의 데이터 및 메타 데이터를 지정된 백업 디렉토리로 내보내게됩니다.

전자 상거래 웹 사이트를 개발할 때 어려운 문제가 발생했습니다. 사용자에게 개인화 된 제품 권장 사항을 제공하는 방법. 처음에는 간단한 권장 알고리즘을 시도했지만 결과는 이상적이지 않았으며 사용자 만족도에도 영향을 미쳤습니다. 추천 시스템의 정확성과 효율성을 향상시키기 위해보다 전문적인 솔루션을 채택하기로 결정했습니다. 마지막으로 Composer를 통해 Andres-Montanez/Residations-Bundle을 설치하여 문제를 해결했을뿐만 아니라 추천 시스템의 성능을 크게 향상 시켰습니다. 다음 주소를 통해 작곡가를 배울 수 있습니다.
