NoSql_笔记


spring data官网:https://spring.io/projects/spring-data

Spring Data JDBC

基于jdbc的数据访问;https://docs.spring.io/spring-data/jdbc/docs/1.0.9.RELEASE/reference/html/
概念:repository–存储库,aggregate root–实体类,aggregate–实体类实例

3 Working with Spring Data Repositories

基于jpa,减少样板代码。

3.1 核心概念

Repository–CrudRepository–PagingAndSortingRepository;具体技术,如JpaRepository(qbe)、MongoRepository
@NoRepositoryBean,不暴露为bean
DSL命名查询,@Query查询语句。
空处理
Optional包装返回结果
@NonNullApi;标记包,形参及返回结果不为null
@NonNull、@Nullable;标记形参、方法,是否可为空
特殊参数
1,Pageable
PageRequest.of();获取PageRequest实例
QPageRequest#new;构造器获取实例,querydsl
2,Sort
默认升序。
new Sort(Direction,String[]/List);
Sort.by();获取实例
QSort.by()、QSort#new;获取QSort实例,QSort继承Sort。
3,属性对象的属性参数命名
建议使用下划线分隔属性对象及其属性;如:findByAddress_ZipCode
自定义实现类
接口、实现类需被扫描到。默认实现类后缀Impl。
根据类名、bean id确定最终实现类。

@EnableJpaRepositories(
		entityManagerFactoryRef="entityManagerFactoryPrimary",
		transactionManagerRef="primaryTransactionManager",//jpa增删改事务
		basePackageClasses = { UserRepository.class },//默认本注解所在包
		//自实现类后缀,默认Impl;接口、实现类必须放在扫描包下
		repositoryImplementationPostfix="Impl" 
	)

事件
save()后调用。
@DomainEvents;标记方法,发布事件。
@AfterDomainEventPublication;标记发布事件后回调方法
@TransactionalEventListener;监听事件,使用@EventListener会在接收到事件后立即处理
https://blog.csdn.net/f4761/article/details/84622317

Spring Data Redis

官网文档
spring data redis:https://docs.spring.io/spring-data/redis/docs/2.1.9.RELEASE/reference/html/
redis运行模式:单点、主从、哨兵、集群;

5 Redis支持

5.3 连接redis

RedisConnectionFactory、RedisConnection。
Lettuce

RedisStandaloneConfiguration rsc = new RedisStandaloneConfiguration("server", 6379);
LettuceConnectionFactory rcf = new LettuceConnectionFactory(rsc);
rcf.setShareNativeConnection(false);//设置不共享底层连接,默认true
RedisConnection conn = rcf.getConnection();
//主从设置;主写从读,最终一致。
LettuceClientConfiguration lcc = LettuceClientConfiguration.builder()
			      .readFrom(ReadFrom.SLAVE_PREFERRED) //优先读从
			      .build();
rcf =new LettuceConnectionFactory(rsc,lcc);

Jedis
JedisConnectionFactory,配置与Lettuce类似。

5.4 哨兵

哨兵为Redis提供高可用,多进程运行。
监视、通知、故障转移、提供配置(客户端通过哨兵获取master地址)。
https://www.jianshu.com/p/c059d374e42d

RedisSentinelConfiguration sentinelConfig = new RedisSentinelConfiguration()
  .master("mymaster")
  .sentinel("127.0.0.1", 26379)
  .sentinel("127.0.0.1", 26380);
lcf = new LettuceConnectionFactory(sentinelConfig);

获取哨兵连接:RedisConnectionFactory#getSentinelConnection();RedisConnection#getSentinelCommands()

5.5 RedisTemplate

模板线程安全,可跨多个实例重用。默认序列化机制为JdkSerializationRedisSerializer。

RedisTemplate rs = new RedisTemplate();
rs.setConnectionFactory(rcf);

通过rs获取不同的操作视图,可直接注入rs,由容器转换;如HashOperations、BoundHashOperations等。

5.6 StringRedisConnection and StringRedisTemplate

RedisConnection、RedisTemplate的扩展;键值均为String,序列化使用StringRedisSerializer。

StringRedisTemplate srt = new StringRedisTemplate();
srt.setConnectionFactory(rcf);

5.7 序列化器

类似spring消息转换器;进程间通信必须转换为字节流、字符流。
序列化器类型:双向(RedisSerializer,基于byte[])、单向(RedisElementReader/RedisElementWriter,基于ByteBuffer)
常用序列化器:

  • JdkSerializationRedisSerializer;默认;允许负载引发的远程代码执行,不安全。Java native serialization is known for allowing remote code execution caused by payloads that exploit vulnerable libraries and classes injecting unverified bytecode.
  • StringRedisSerializer;StringRedisTemplate默认。
  • Jackson2JsonRedisSerializer、GenericJackson2JsonRedisSerializer;转json
  • OxmSerializer转xml

RedisConnection#setter设置序列化器。

5.8 Hash映射

RedisTemplate#opsForHash();
将数据映射到hash(转为Map结构)存储的策略:

  • HashOperations+序列化器/HashMapper
  • Redis Repository

HashMapper实现类:ObjectHashMapper(byte[], byte[])、Jackson2HashMapper(String, Object)
HashMapper#tohash()/fromHash();转换对象

5.9 消息发布订阅

消息发布
RedisConnection#publish();
RedisTemplate#convertAndSend();//转为byte[]后通过前者发送
消息订阅
消息模式:direct、topic、broadcast

5.10 事务

Redis事务支持:

  • RedisTemplate#multi()/exec()/discard();标记事务开始、执行、回滚

RedisTemplate不保证所有的操作使用同一个connection。
SessionCallback接口,封装事务流程,保证同一连接执行。RedisTemplate#execute()
@Transactional支持
编程式事务
默认情况下,RedisTemplate禁用事务;RedisTemplate#setEnableTransactionSupport(true)开启。
开启后可通过事务管理器管理事务;进入时multi(绑定connection、thread),执行异常discard,无异常exec。事务中,所有的readonly操作,分配给非绑定连接执行。
注解式事务
基于DataSource,配置普通PlatformTransactionManager,提供事务管理器。
@EnableTransactionManagement,开启注解事务。

5.11 Pipelining

发送多个command,统一接收回复。类似Statement#addBatch()。

  • RedisTemplate#execute(pipeline=true);无返回结果
  • RedisTemplate#executePipelined();有返回结果

RedisCall返回值必须为null,返回值会被执行结果重写。

7 Redis集群

原节点数a,增加后节点数b;还能正常访问的key:a/ab的最小公倍数。

7.1 RedisConnectionFactory

使用RedisClusterConfiguration构建RedisConnectionFactory。

RedisClusterConfiguration rcc = new RedisClusterConfiguration(nodes);//nodes为host:port的List。
RedisConnectionFactory rcf = new LettuceConnectionFactory(rcc);

7.2 RedisClusterConnection

集群映射key到16384个槽中,节点持有分配的槽位。
执行包含多个key的命令时,需保证key在相同槽位中;否则报跨槽错误。
key包含{EXP}时,通过EXP计算槽位;否则通过key计算。
RedisClusterConnection提供了跨槽操作;当所有key映射到同一插槽中,合并执行(MGET),否则逐一执行。
RedisConnectionFactory#getClusterConnection();获取集群连接

7.3 ClusterOperations

RedisTemplate#opsForCluster();获取ClusterOperations

8 Redis Repositories

类似JPA。不能使用事务。

8.1 Usage

与jpa类似。
1,@RedisHash标记entity类,@org.springframework.data.annotation.Id标记key属性。
2,继承Repository、CrudRepository;添加自定义方法
3,配置RedisConnectionFactory、RedisTemplate
4,@EnableRedisRepositories开启

8.2 对象映射

对象创建
通过构造器构建对象,多个构造器时,@PersistenceConstructor标记需要使用的构造器。
@ConstructorProperties,匹配构造器参数、实例属性。
spring data运行时通过工厂类构建对象,避免反射开销;要求实体类:不能是私有类、非静态内部类、cglib代理类,且构造函数非私有。否则使用反射实例化。

8.3 对象到哈希映射

默认使用ObjectHashMapper转换。
@TypeAlias,转为hash时类名。

8.4 Keyspaces

redis键格式,keySpace:id。
keySpace默认为类全名。
@RedisHash#value,设置keySpace,优先级最高。
@EnableRedisRepositories#keySpaceConfiguration,配置策略

8.5 第二索引

数据库索引。
@Indexed;标记索引属性,优先级最高。
@EnableRedisRepositories#indexConfiguration,配置策略

8.7 有效期

@RedisHash#timeToLive;有效期
@TimeToLive;有效期,标记属性/getter方法。

8.8 Persisting References

类似@OneToOne
@Reference;标记对象属性,存储时分开存储,通过keySpace:id关联。

8.9 Persisting Partial Update

部分更新,HashOperations#put()。

PartialUpdate<Person> update = new PartialUpdate<Person>("e2c7dcee", Person.class)
  .set("firstname", "mat")                                                           
  .set("address.city", "emond's field")                                              
  .del("age");

8.10 查询

构建查询方法时,确保finder方法使用的属性已设置为索引。标记@Indexed。
Redis repository仅支持集合、分页查询。

8.11 集群

keySpace声明为"{keyspace}",使用特定的插槽来定义和固定键空间。
@RedisHash("{person}")

SpringBoot整合

用做cache(spring.cache)、session(spring.session)、nosql(spring.redis)。
redis运行方式:单点、主从、哨兵、集群;
手动配置多redis:https://blog.csdn.net/zhufengyan521521/article/details/89971273

Configuration

RedisConfiguration环境配置,LettuceClientConfiguration/JedisClientConfiguration客户端配置
RedisConfiguration环境配置实现类:

  • RedisStandaloneConfiguration;单点,spring.redis
  • RedisSentinelConfiguration;哨兵,spring.redis.rentinel
  • RedisClusterConfiguration;集群,spring.redis.cluster

LettuceClientConfiguration客户端配置实现类:

  • DefaultLettuceClientConfiguration;LCC接口默认实现类,LCC.builder()构建。
  • MutableLettuceClientConfiguration;连接工厂实现类,无readFrom、clientOption
  • DefaultPoolingLettuceClientConfiguration;池化接口默认实现类,接口builder()构建。连接池通过common-pool2#GenericObjectPoolConfig配置。

JedisClientConfiguration客户端配置实现类,common-pool2#GenericObjectPoolConfig管理连接池:

  • DefaultJedisClientConfiguration;默认实现类
  • MutableJedisClientConfiguration;连接工厂实现类

Elasticsearch

https://docs.spring.io/spring-data/elasticsearch/docs/3.1.9.RELEASE/reference/html/

1 配置连接

@EnableElasticsearchRepositories;启用
@Document;标记实体类
@Field;标记列
连接es,自动配置:

  • elasticsearch-rest-client#RestClient;配置spring.elasticsearch.rest.*
  • elasticsearch-rest-high-level-client#RestHighLevelClient;
  • jest#Jest;实现HttpClientConfigBuilderCustomizer,定制JestClient。配置spring.elasticsearch.jest.*
  • ElasticsearchTemplate、TransportClient;spring data方式。配置spring.data.elasticsearch.*

手动配置:https://msd.misuland.com/pd/9101278712788455?page=1

2 查询方法

DSL方式命名,或者@Query指定sql。
查询构建策略默认:Key.CREATE_IF_NOT_FOUND
@Query指定查询结构,学习es查询语法。

3,其他es操作

复杂查询,使用JestClient、TransportClient等进行。
https://www.jianshu.com/p/00156c138756
https://yq.aliyun.com/articles/70011?spm=5176.10695662.1996646101.searchclickresult.61812eba7yusk4

注意

1,es版本与jar包版本一致
2,通过spring data方式连接es,端口必须填写tcp端口。
3,es contains必须为全小写,like无要求

查询构建

QBE(Query By Example)

https://www.jianshu.com/p/3a98c3969b4b
核心接口:QueryByExampleExecutor、Example、ExampleMatcher
JpaRepository继承PagingAndSortingRepository、QueryByExampleExecutor。

Example

Example.of();创建Example实例。

ExampleMatcher

条件策略。默认只判非空属性
创建实例
ExampleMatcher.matching()/matchingAll();属性完全相等,MatchMode.ALL
ExampleMatcher.matchingAny();任意属性相等,MatchMode.ANY
模式相关
isAllMatching()/isAnyMatching();
属性相关
withIgnorePaths(strs);不匹配strs属性
getIgnoredPaths();
isIgnoredPath();
字符串匹配
withStringMatcher();设置默认字符串匹配策略,StringMatcher。
getDefaultStringMatcher();
withIgnoreCase();重载,设置默认忽略大小写,设置忽略大小写属性
isIgnoreCaseEnabled();默认忽略大小写
对象匹配
withMatcher();属性匹配策略,GenericPropertyMatcher。
withTransformer();属性转换策略,PropertyValueTransformer
空值策略
withIncludeNullValues();匹配null值
withIgnoreNullValues();忽略null值,默认
withNullHandler();设置空值策略,NullHandler
getNullHandler();获取空值策略

相关枚举类

MatchMode
匹配模式;值:ALL、ANY
NullHandler
null值处理;值:INCLUDE、IGNORE
StringMatcher
字符串匹配模式;值:DEFAULT、EXACT、STARTING、CONTAINING、ENDING、REGEX
NoOpPropertyValueTransformer
对象转字符串;值:INSTANCE

其他类

GenericPropertyMatcher
通用属性匹配策略,将属性转为字符串后匹配。
属性:

  • StringMatcher、Boolean-ignoreCase;
  • PropertyValueTransformer;转换策略,默认NoOpPropertyValueTransformer.INSTANCE

GenericPropertyMatcher.of()/GenericPropertyMatcher#new;构建实例
GenericPropertyMatchers工具类构建
PropertyValueTransformer
匹配前转换属性。函数式接口。
实现类NoOpPropertyValueTransformer.INSTANCE,直接返回。
需自己重写,可通过主键判定。

QueryDSL

示例:https://www.jianshu.com/p/99a5ec5c3bd5
核心类:QueryFactory+Query、QuerydslPredicateExecutor、Q查询类、Predicate
官网文档:https://github.com/querydsl/querydsl

maven配置

导包:com.querydsl#querydsl-apt,com.querydsl#querydsl-jpa
导入插件:

    <plugin>
      <groupId>com.mysema.maven</groupId>
      <artifactId>apt-maven-plugin</artifactId>
      <version>1.1.3</version>
      <executions>
        <execution>
          <goals>
            <goal>process</goal>
          </goals>
          <configuration>
            <outputDirectory>target/generated-sources/java</outputDirectory>
            <processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
          </configuration>
        </execution>
      </executions>
    </plugin>

注意
1,若实体类使用Hibernate注解,则插件换为com.querydsl.apt.hibernate.HibernateAnnotationProcessor。
2,运行mvn clean install,生成查询类,路径:target/generated-sources/java
3,eclipse运行mvn eclipse:eclipse,将target/generated-sources/java导入。

查询类

运行mvn clean install,插件生成查询类;命名:QEntityName,如QCustomer
获取实例

QCustomer customer = QCustomer.customer;
QCustomer customer = new QCustomer("customer ");

原生查询

基于QueryFactory、Query进行查询。
jpa实现类:JPAQueryFactory、JPAQuery
hibernate实现类:HibernateQueryFactory 、HibernateQuery
流式api添加条件:

Customer bob = queryFactory.selectFrom(customer)
  .where(customer.firstName.eq("Bob"))
  .fetchOne();

spring-data整合查询

repository继承QuerydslPredicateExecutor

ES查询构建QueryBuilders

构建StringQuery查询;new StringQuery(qb.toString())
https://blog.csdn.net/zhaipengfei1231/article/details/80230902
官网DSL:https://www.elastic.co/guide/en/elasticsearch/reference/6.2/query-dsl.html
ES查询语句分两类:

  • 子查询语句;查询特定字段的特定值,如match、term、range
  • 复合查询语句;组合多个子查询语句,如bool、dis_max、constant_score

ES查询语境:查询(query context,评分)、过滤(filter context,只匹配不评分)

查询语句

查询语句大体分8类:
Match All Query;match_all匹配全部文档,match_none不匹配任何文档。
Full text query;全文检索,match、multi_match等。
Term level queries;关键词匹配,term、terms、range等。
compound queries;组合子查询,bool、constant_score等。
joining queries;关联查询,nested、has_child、has_parent。
geo queries;地理信息查询。
specialized queries;特殊查询,more_like_this、wrapper、script等。
span queries;跨度查询。

RestClient

使用RestClient查询,需将查询包在{“query”:{EXPR}}
RestClient可进行增删改查操作,批量操作bulk。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值