diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9243c63 --- /dev/null +++ b/.gitignore @@ -0,0 +1,26 @@ +.gradle +/build/ +!gradle/wrapper/gradle-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..6df6278 --- /dev/null +++ b/README.md @@ -0,0 +1,603 @@ +SpringBoot2.0 + NoSQL使用教程, + +## 项目介绍 +All in one一站式SpringBoot for NoSQL开发教程手册。 + +含SpringBoot2.0 + Redis、Ehcache、MongoDB、ElasticSearch、Cassandra、CouchBase、Solr、Neo4j、Gemfire共10种常用NoSQL数据库操作、工具类、演示代码。 + + +重点介绍Redis、MongoDB、ElasticSeach、Cassandra四种数据库,因为它们是各自领域的领先者(分别是KV缓存、文档数据库、搜索数据库、列数据库)。 + +## Redis for SpringBoot 开发介绍 + +内容: + +- SpringBoot配置、控制器、Repository Crud; +- string、list、set、zset、hash操作; +- 同步、异步操作; +- 管道批处理; +- 分布式对象操作:对象桶Object Bucket、二进制流Binary Stream、原子类型、发布订阅、HyperLogLog分布式基数估计算法等;分布式锁; +- 分布式集合操作:哈希、多值哈希、集合、排序集合、队列(双端、阻塞、有界、公平、延迟、优先) +- 性能测试、内存监控 +- 注意:在启动SpringBoot前要先启动Redis服务。 + +##### application.properties配置: + + # Redis + # Redis数据库索引(默认为0) + spring.redis.database=0 + spring.redis.host=127.0.0.1 + spring.redis.port=6379 + #spring.redis.password=123 + # 连接池最大连接数(使用负值表示没有限制) + spring.redis.pool.max-active=60 + # 连接池中的最大空闲连接 + spring.redis.pool.max-idle=30 + # 连接池最大阻塞等待时间(使用负值表示没有限制) + spring.redis.pool.max-wait=-1 + # 连接池中的最小空闲连接 + spring.redis.pool.min-idle=0 + + #redisson配置 + #redis链接地址 + spring.redisson.address=redis://127.0.0.1:6379 + ... + +因为我们还使用了Redisson作为客户端,还需RedissonConfig + + @ConfigurationProperties(prefix = "spring.redisson") + @Configuration + public class RedissonConfig{ + ... + +Spring官方默认支持Lettuce、Jedis客户端,Redis官方的推荐客户端是Redisson,因为Redison提供了诸多分布式的集合工具(这对单机到分布式的扩展非常有益)以及优异的性能,所以非常值得使用Redisson客户端。Spring Boot是一个平台,不必受限于它。我们在代码中配置Redisson连接的模式是单机模式,如想配置集群模式和哨兵模式,请参考官方wiki: https://github.com/redisson/redisson/wiki/ + +##### 模型Model: +见xy.SpringBoot2NoSQL.model.Redis.User + + public class User implements Serializable{ + + private String login; + private String fullName; + ... + + +这完全是一个简单POJO java类.使用登录名(login)作为关键字段。 + +##### 数据层repository: +xy.SpringBoot2NoSQL.repository.Redis.**ObjectRepository** + +以及 + +xy.SpringBoot2NoSQL.repository.Redis.**UserRepository** + +分别是Object类型转换操作的数据类,和泛型User数据操作. + +两者都是扩展自org.springframework.data.redis.core.**ValueOperations** +CRUD操作是RedisTemplate中提供了几个常用的单例对象,全面满足Redis的5大数据结构外,还提供了如地理位置、计数估计HyperLogLog操作。如: + + private @Nullable ValueOperations valueOps;//KV操作 + private @Nullable ListOperations listOps;//列表 + private @Nullable SetOperations setOps;//无排序集合 + private @Nullable ZSetOperations zSetOps;//计分排序集合 + private @Nullable GeoOperations geoOps;//用于地理位置 + private @Nullable HyperLogLogOperations hllOps;//基数估值 + ... + @Override + public ValueOperations opsForValue() { + + if (valueOps == null) { + valueOps = new DefaultValueOperations<>(this); + } + return valueOps; + } + ... + @Override + public ZSetOperations opsForZSet() { + + if (zSetOps == null) { + zSetOps = new DefaultZSetOperations<>(this); + } + return zSetOps; + } + ... + +在RedisTemplate中,已经提供了一个工厂方法:opsForValue()。这个方法会返回一个默认的操作类。另外,我们可以直接通过注解@Resource(name = “redisTemplate”)来进行注入。 + + +##### 控制器controller: +见xy.SpringBoot2NoSQL.controller.Redis.**RedisDataController** + + @RestController + @RequestMapping("/redis") + public class RedisDataController { + + @Autowired + ObjectRepository objRepository; + @Autowired + StringStringRepository stringStringRepository; + + @RequestMapping("/add/{name}") + public String getRecognition(@PathVariable("name") String name){ + User user = new User(name,name); + objRepository.save(user); + + return "add success."; + } + + @RequestMapping("/user/{name}") + public User getUser(@PathVariable("name") String name){ + return (User)objRepository.get(name); + + } + } + +具体代码不再赘述。 +另外,提供了Redisson的控制器: + +xy.SpringBoot2NoSQL.controller.Redis.**RedissonController** + +RedissonController演示了同步\异步操作、分布式集合(哈希、多值哈希、集合、排序集合、队列)、本地缓存、对象桶Object Bucket、二进制流Binary Stream、原子类型、发布订阅、HyperLogLog分布式基数估计算法、累加器、元素淘汰、事件监听、分布式锁、异步批量操作等。 + +比如本地缓存操作: + + @RequestMapping("/getLocalCachedMap/{name}/{key}") + public String getLocalCachedMap(@PathVariable("name") String name,@PathVariable("key") String key){ + + LocalCachedMapOptions options = LocalCachedMapOptions.defaults() + .evictionPolicy(LocalCachedMapOptions.EvictionPolicy.LFU) + .cacheSize(100) + .syncStrategy(LocalCachedMapOptions.SyncStrategy.UPDATE) //同步缓存 + .timeToLive(10, TimeUnit.SECONDS) + .maxIdle(10, TimeUnit.SECONDS); + + RLocalCachedMap map = redisson.getLocalCachedMap(name,options); + map.put(key, "测试值"); + String result = (String)map.get(key); + return result; + } + +##### 运行效果 + +##### 更多详细介绍 + +正在写作... + +## Ehcache for SpringBoot 开发介绍 + +##### application.properties配置: + + # ehcache + spring.cache.type=ehcache + spring.cache.ehcache.config=classpath:ehcache.xml + +ehcache.xml + + + + + + + + + + + + +##### 模型Model: +见xy.SpringBoot2NoSQL.model.User +这完全是一个简单POJO java类.使用登录名(login)作为关键字段。 + + public class User implements Serializable{ + + private String login; + private String fullName; + ... + + +##### 数据服务层Service: +见xy.SpringBoot2NoSQL.service.Ehcache.UserService + +演示简单直接,并没有repository。 getUser() 方法演示了缓存根据配置存在于JVM堆、堆外、磁盘持久化的各种情况。 + +##### 控制器controller: +见xy.SpringBoot2NoSQL.controller.Ehcache.EhcacheDataController + + + + +## MongoDB for SpringBoot 开发介绍 +##### application.properties配置: + + # MONGODB + spring.data.mongodb.host=127.0.0.1 + spring.data.mongodb.port=27017 + spring.data.mongodb.database=test + +##### 模型Model: +见xy.SpringBoot2NoSQL.model.Mongo.Person + + @Document + public class Person { + @Id + private String id; + private String name; + private Integer age; + @Field("locs") + private Collection locations = new LinkedHashSet(); + @DBRef + Department department; + +@Document是org.springframework.data.mongodb.core.mapping.Document的注解。 + +@Id是定义主键。 + +@Field("locs")是定义文档内部对象,在这里是Collection + +@DBRef是链接到外表,Department是链接的表,有点像关系数据库的Inner Join,以Department的id关联。 + + +##### 数据层repository: +见xy.SpringBoot2NoSQL.repository.Mongo.PersonRepository + +继承MongoRepository接口,其中T为仓库保存的bean类,TD为该bean的唯一标识的类型,一般为ObjectId。之后在service中注入该接口就可以使用,无需实现里面的方法,spring会根据定义的规则自动生成。 + + + import org.springframework.data.domain.Page; + import org.springframework.data.domain.Pageable; + import org.springframework.data.mongodb.repository.MongoRepository; + import org.springframework.data.mongodb.repository.Query; + import xy.SpringBoot2NoSQL.model.Mongo.Person; + import java.util.List; + + public interface PersonRepository extends MongoRepository { + + Person findByName(String name); + + @Query("{'age': { '$lt' : ?0}}") + List withQueryFindByAge(Integer age); + + Page findAll(Pageable pageable); + + } + +自定义查询方法,还可以使用格式为“findBy+字段名+方法后缀”,方法传进的参数即字段的值,此外还支持分页查询,通过传进一个Pageable对象,返回Page集合。 +如查询大于age的数据: + + public Page findByAgeGreaterThan(int age,Pageable page) ; + +也可以使用mongodb原生查询语句,使用@Query注解,如: + + @Query("{'age': { '$lt' : ?0}}") + List withQueryFindByAge(Integer age); + + //大于 + {"age" : {"$gt" : age}} + //小于 + {"age" : {"$lt" : age}} + //之间 + findByAgeBetween(int from, int to) + {"age" : {"$gt" : from, "$lt" : to}} + //非空 + findByFirstnameNotNull() + {"age" : {"$ne" : null}} + //模糊查询 + findByFirstnameLike(String name) + {"age" : age} ( age as regex) + //非 + findByFirstnameNot(String name) + {"age" : {"$ne" : name}} + +##### 控制器controller: +见xy.SpringBoot2NoSQL.controller.Mongo.MongoDataController + + @RestController + @RequestMapping("/mongo") + public class MongoDataController { + + @Autowired + PersonRepository personRepository; + @Autowired + DepartmentRepository departmentRepository; + + @RequestMapping("/persons/{name}") + public Person getPerson(@PathVariable("name") String name){ + return personRepository.findByName(name); + } + + @GetMapping("findAll") + public List getUserList() { + List userInfoList = personRepository.findAll(); + return userInfoList; + } + + @GetMapping("insert") + public Person insert(Long id, String username, String password) { + Person user = new Person("test2",22); + return personRepository.insert(user); + } + + @DeleteMapping("/colleagues/{name}") + public ResponseEntity deleteColleague(@PathVariable String name){ + Person person = personRepository.findByName(name); + if(person!=null) { + personRepository.delete(person); + return new ResponseEntity<>(HttpStatus.ACCEPTED); + } + return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + } + ... +具体CRUD不再赘述。 + + +## ElasticSearch for SpringBoot 开发介绍 + +##### application.properties配置: + + # elasticsearch + #节点名字,默认elasticsearch + spring.data.elasticsearch.cluster-name=elasticsearch + # 节点地址,多个节点用逗号隔开 + spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300 + #spring.data.elasticsearch.local=false + spring.data.elasticsearch.repositories.enable=true + +##### 模型Model: +见xy.SpringBoot2NoSQL.model.ElasticSearch.Product + + @Document(indexName = "book",type = "book" , shards = 1, replicas = 0, refreshInterval = "-1") + public class Product { + @Id + private String id; + private String name; + ... +Elasticsearch是面向文档(document oriented)的,这意味着它可以存储整个对象或文档(document)。然而它不仅仅是存储,还会索引(index)每个文档的内容使之可以被搜索。在Elasticsearch中,你可以对文档(而非成行成列的数据)进行索引、搜索、排序、过滤。 + +在Elasticsearch中存储数据的行为就叫做索引(indexing),不过在索引之前,我们需要明确数据应该存储在哪里。 +在Elasticsearch中,文档归属于一种类型(type),这里是Classname(即book),而这些类型存在于索引(index)中,我们可以画一些简单的对比图来类比传统关系型数据库: + + Relational DB -> Databases -> Tables -> Rows -> Columns + Elasticsearch -> Indices -> Types -> Documents -> Fields + +Elasticsearch集群可以包含多个索引(indices)(数据库),每一个索引可以包含多个类型(types)(表),每一个类型包含多个文档(documents)(行),然后每个文档包含多个字段(Fields)(列,比如name、age...)。文档中的所有字段都会被索引(拥有一个倒排索引),只有这样他们才是可被搜索的。注意:传统数据库为特定列增加一个索引,一般使用B-Tree索引,Elasticsearch和Lucene使用一种叫做倒排索引(inverted index)的数据结构。 + + +##### 数据层repository: +见xy.SpringBoot2NoSQL.repository.ElasticSearch.SampleProductRepository + + public interface SampleProductRepository extends ElasticsearchRepository { + List findByName(String name); + List findByDescription(String description); + List findByName(String name, Pageable pageable); + List findByNameAndId(String name, String id); + } + +通过继承ElasticsearchRepository来完成基本的CRUD及分页操作的,和普通的JPA没有什么区别。ElasticsearchRepository继承了ElasticsearchCrudRepository extends PagingAndSortingRepository。 + +另外还可以使用ElasticSearchTemplate,ElasticSearchTemplate更多是对ESRepository的补充,里面提供了一些更底层的方法,主要是一些查询相关的,同样是构建各种SearchQuery条件。比如我们经常需要往ElasticSearch中插入大量的测试数据来完成测试搜索,一条一条插肯定是不行的,ES提供了批量插入数据的功能——bulk。 +JPA的save方法也可以save(List)批量插值,但适用于小数据量,要完成超大数据的插入就要用ES自带的bulk了,可以迅速插入百万级的数据。 +在ElasticSearchTemplate里也提供了对应的方法。 + +##### 控制器controller: +用于CRUD操作: + +xy.SpringBoot2NoSQL.controller.ElasticSearch.ESDataController + +用于查询操作: + +xy.SpringBoot2NoSQL.controller.ElasticSearch.ESSearchController + +其中matchQuery、fuzzyQuery、termsQuery等查询的区别可见: + + + @GetMapping("searchProduct/{key}/{value}/{searchtype}") + public Page searchProduct(@PathVariable String key,@PathVariable String value, @PathVariable String searchtype) { + Page products = null; + + if (searchtype.equals("matchQuery")) { + products = sampleProductRepository.search(ESSearchUtil.matchQuery(key, value), PageRequest.of(0, 5)); + } + + if (searchtype.equals("matchPhraseQuery")) { + products = sampleProductRepository.search(ESSearchUtil.matchPhraseQuery(key, value), PageRequest.of(0, 5)); + } + + if (searchtype.equals("fuzzyQuery")) { + products = sampleProductRepository.search(ESSearchUtil.fuzzyQuery(key, value), PageRequest.of(0, 5)); + } + + if (searchtype.equals("termsQuery")) { + products = sampleProductRepository.search(ESSearchUtil.termsQuery(key, value), PageRequest.of(0, 5)); + } + + return products; + } + +组合查询: + + public QueryBuilder getBoolQuery() { + + return QueryBuilders.boolQuery() + .must(QueryBuilders.matchPhraseQuery("name", "测试产品1")) + //.mustNot(QueryBuilders.termQuery("enabled", true)); + .must(QueryBuilders.matchPhraseQuery("enabled", true)); + } + + +## Cassandra for SpringBoot 开发介绍 +##### 内容 +- SpringBoot配置、控制器、Repository Crud; +- 使用前需要先建表,建表的脚本见“脚本”》“Cassandra”》“建库脚本.txt” +- 注意:如果是3.9版本的Win64的DataStax-DDC版本安装后,是无法启动服务的,需要修改配置文件,配置cdc_raw_directory类似如下: +cdc_raw_directory: "你的cdcraw目录" +,如果是2.X版不存在这个问题。 +- 注意:在启动SpringBoot前必须先启动Cassandra服务。 + +##### 配置: + +cassandra.properties + + #cassandra.properties + cassandra.contactpoints=127.0.0.1 + cassandra.port=9042 + cassandra.keyspace=mydb + +CassandraConfig类 + + @Configuration + @PropertySource(value = { "classpath:cassandra.properties" }) + @EnableCassandraRepositories(basePackages = "xy.SpringBoot2NoSQL.repository.Cassandra") + public class CassandraConfig extends AbstractCassandraConfiguration { + @Autowired + private Environment environment; + + @Override + protected String getKeyspaceName() { + return environment.getProperty("cassandra.keyspace"); + } + + @Override + @Bean + public CassandraClusterFactoryBean cluster() { + ... + } + + @Override + @Bean + public CassandraMappingContext cassandraMapping() throws ClassNotFoundException { + ... + } + + } + +##### 模型Model: + + @Table + public class Customer { + + @PrimaryKey + private String id; + private String firstname; + ... + get、set + ... + +@Table定义了一个持久化的 Cassandra表,@PrimaryKey指定了主键字段,PrimaryKey是Cassandra中用于获取一行数据的key依据。 +可以把Cassandra的数据结构理解为Map> + +主要语句是: + + CREATE TABLE customer( + id text PRIMARY KEY,... +是不是有点像关系数据库? +如果想设置自增的key,可以用SERIAL替代text + +##### 数据层repository: + + public interface CustomerRepository extends CassandraRepository { + + @Query(value="SELECT * FROM customer WHERE firstname=?0") + public List findByFirstname(String firstname); + + @Query("SELECT * FROM customer WHERE age > ?0") + public List findCustomerHasAgeGreaterThan(int age); + + @AllowFiltering + public List findByLastname(String lastname); + + @AllowFiltering + public List findByAgeGreaterThan(int age); + } +和CrudRepository的使用和扩展一样,增删改查一应俱全了,不再赘述。 +CassandraRepository继承于org.springframework.data.repository的CrudRepository +其中ID是primary key的类型,支持单一的key,如果是复合主键(compound primary key),则需要使用{@link MapId}手动定义键值使用。 +@AllowFiltering用于扩展查询,他的作用是不使用@Query注解,而直接使用字段名来查询,还支持大于、小于等操作,但@Query还是来的更直观一些。 + +##### 控制器controller: + + @RestController + @RequestMapping("/cassandra") + public class CassandraController { + + Logger logger = LogManager.getLogger(getClass()); + + @Autowired + CustomerRepository customerRepository; + + @RequestMapping("/add") + public String add(){ + customerRepository.deleteAll(); + Customer cust_1 = new Customer("Test1", "Test1", "Test1", 20); + Customer cust_2 = new Customer("Test2", "Test2", "Test2", 25); + customerRepository.save(cust_1); + customerRepository.save(cust_2); + + return "ok"; + }... + +增删改查操作不再赘述。 + +##### 运行效果 + +##### 更多详细介绍 + +正在写作... + +## CouchBase for SpringBoot 开发介绍 + + +##### application.properties配置: + + #Couchbase + spring.couchbase.bootstrap-hosts=127.0.0.1 + spring.couchbase.bucket.name=mydb + spring.couchbase.bucket.password=123456 + spring.data.couchbase.auto-index=true +##### 模型Model: +见xy.SpringBoot2NoSQL.model.Couchbase.Customer +##### 数据层repository: +见xy.SpringBoot2NoSQL.repository.Couchbase.CouchbaseCustomerRepository +##### 控制器controller: +见xy.SpringBoot2NoSQL.controller.Couchbase.CouchbaseController + + +## Solr for SpringBoot 开发介绍 +##### application.properties配置: + + spring.data.solr.host=http://localhost:8983/solr +##### 模型Model: +见xy.SpringBoot2NoSQL.model.Solr.Customer +##### 数据层repository: +见xy.SpringBoot2NoSQL.repository.Solr.SolrCustomerRepository +##### 控制器controller: +见xy.SpringBoot2NoSQL.controller.Solr.SolrController + + +## Neo4j for SpringBoot 开发介绍 +正在写作... + +## Gemfire for SpringBoot 开发介绍 +正在写作... + +## Hadoop家族 for SpringBoot 开发介绍 +准备另开一个项目,不在此工程(SpringBoot2NoSQL)中,新项目将命名为“SpringBoot2Hadoop” \ No newline at end of file diff --git a/bin/main/application.properties b/bin/main/application.properties new file mode 100644 index 0000000..79c7f91 --- /dev/null +++ b/bin/main/application.properties @@ -0,0 +1,101 @@ +server.port=9092 +debug=true +spring.devtools.restart.exclude=static/** + +#spring.datasource.url=jdbc:mysql://localhost:3306/boot?useUnicode=true&zeroDateTimeBehavior=convertToNull&autoReconnect=true +#spring.datasource.username=root +#spring.datasource.password=mysql +#spring.datasource.driver-class-name=com.mysql.jdbc.Driver + +# MONGODB +spring.data.mongodb.host=127.0.0.1 +spring.data.mongodb.port=27017 +spring.data.mongodb.database=test + +#Cassandra +#spring.data.cassandra.keyspace-name=mydb +#spring.data.cassandra.contact-points=localhost +#spring.data.cassandra.port=9042 + +#Solr +spring.data.solr.host=http://localhost:8983/solr + +#Couchbase +#spring.couchbase.bootstrap-hosts=127.0.0.1 +#spring.couchbase.bucket.name=mydb +#spring.couchbase.bucket.password=123456 +#spring.data.couchbase.auto-index=true + +# Redis +# Redis\u6570\u636e\u5e93\u7d22\u5f15\uff08\u9ed8\u8ba4\u4e3a0\uff09 +spring.redis.database=0 +spring.redis.host=127.0.0.1 +spring.redis.port=6379 +#spring.redis.password=123 +# \u8fde\u63a5\u6c60\u6700\u5927\u8fde\u63a5\u6570\uff08\u4f7f\u7528\u8d1f\u503c\u8868\u793a\u6ca1\u6709\u9650\u5236\uff09 +spring.redis.pool.max-active=60 +# \u8fde\u63a5\u6c60\u4e2d\u7684\u6700\u5927\u7a7a\u95f2\u8fde\u63a5 +spring.redis.pool.max-idle=30 +# \u8fde\u63a5\u6c60\u6700\u5927\u963b\u585e\u7b49\u5f85\u65f6\u95f4\uff08\u4f7f\u7528\u8d1f\u503c\u8868\u793a\u6ca1\u6709\u9650\u5236\uff09 +spring.redis.pool.max-wait=-1 +# \u8fde\u63a5\u6c60\u4e2d\u7684\u6700\u5c0f\u7a7a\u95f2\u8fde\u63a5 +spring.redis.pool.min-idle=0 + +#redisson\u914d\u7f6e +#redis\u94fe\u63a5\u5730\u5740 +spring.redisson.address=redis://127.0.0.1:6379 +#\u5f53\u524d\u5904\u7406\u6838\u6570\u91cf * 2 +spring.redisson.thread=4 +#\u6307\u5b9a\u7f16\u89e3\u7801 +spring.redisson.codec=org.redisson.codec.JsonJacksonCodec +#\u6700\u5c0f\u7a7a\u95f2\u8fde\u63a5\u6570,\u9ed8\u8ba4\u503c:10,\u6700\u5c0f\u4fdd\u6301\u8fde\u63a5\u6570\uff08\u957f\u8fde\u63a5\uff09 +spring.redisson.connectionMinimumIdleSize=12 +#\u8fde\u63a5\u7a7a\u95f2\u8d85\u65f6\uff0c\u5355\u4f4d\uff1a\u6beb\u79d2 \u9ed8\u8ba410000;\u5f53\u524d\u8fde\u63a5\u6c60\u91cc\u7684\u8fde\u63a5\u6570\u91cf\u8d85\u8fc7\u4e86\u6700\u5c0f\u7a7a\u95f2\u8fde\u63a5\u6570\uff0c +#\u800c\u8fde\u63a5\u7a7a\u95f2\u65f6\u95f4\u8d85\u8fc7\u4e86\u8be5\u6570\u503c\uff0c\u8fd9\u4e9b\u8fde\u63a5\u5c06\u4f1a\u81ea\u52a8\u88ab\u5173\u95ed\uff0c\u5e76\u4ece\u8fde\u63a5\u6c60\u91cc\u53bb\u6389 +spring.redisson.idleConnectionTimeout=10000 +#ping\u8282\u70b9\u8d85\u65f6,\u5355\u4f4d\uff1a\u6beb\u79d2,\u9ed8\u8ba41000 +spring.redisson.pingTimeout=1000 +#\u8fde\u63a5\u7b49\u5f85\u8d85\u65f6,\u5355\u4f4d\uff1a\u6beb\u79d2,\u9ed8\u8ba410000 +spring.redisson.connectTimeout=10000 +#\u547d\u4ee4\u7b49\u5f85\u8d85\u65f6,\u5355\u4f4d\uff1a\u6beb\u79d2,\u9ed8\u8ba43000\uff1b\u7b49\u5f85\u8282\u70b9\u56de\u590d\u547d\u4ee4\u7684\u65f6\u95f4\u3002\u8be5\u65f6\u95f4\u4ece\u547d\u4ee4\u53d1\u9001\u6210\u529f\u65f6\u5f00\u59cb\u8ba1\u65f6 +spring.redisson.timeout=3000 +#\u547d\u4ee4\u5931\u8d25\u91cd\u8bd5\u6b21\u6570\uff0c\u9ed8\u8ba4\u503c:3 +spring.redisson.retryAttempts=2 +#\u547d\u4ee4\u91cd\u8bd5\u53d1\u9001\u65f6\u95f4\u95f4\u9694\uff0c\u5355\u4f4d\uff1a\u6beb\u79d2,\u9ed8\u8ba4\u503c:1500 +spring.redisson.retryInterval=1500 +#\u91cd\u65b0\u8fde\u63a5\u65f6\u95f4\u95f4\u9694\uff0c\u5355\u4f4d\uff1a\u6beb\u79d2,\u9ed8\u8ba4\u503c\uff1a3000;\u8fde\u63a5\u65ad\u5f00\u65f6\uff0c\u7b49\u5f85\u4e0e\u5176\u91cd\u65b0\u5efa\u7acb\u8fde\u63a5\u7684\u65f6\u95f4\u95f4\u9694 +spring.redisson.reconnectionTimeout=3000 +#\u6267\u884c\u5931\u8d25\u6700\u5927\u6b21\u6570, \u9ed8\u8ba4\u503c\uff1a3\uff1b\u5931\u8d25\u540e\u76f4\u5230 reconnectionTimeout\u8d85\u65f6\u4ee5\u540e\u518d\u6b21\u5c1d\u8bd5\u3002 +spring.redisson.failedAttempts=2 +#\u8eab\u4efd\u9a8c\u8bc1\u5bc6\u7801 +#spring.redisson.password= +#\u5355\u4e2a\u8fde\u63a5\u6700\u5927\u8ba2\u9605\u6570\u91cf\uff0c\u9ed8\u8ba4\u503c\uff1a5 +spring.redisson.subscriptionsPerConnection=5 +#\u5ba2\u6237\u7aef\u540d\u79f0 +#spring.redisson.clientName= +#\u53d1\u5e03\u548c\u8ba2\u9605\u8fde\u63a5\u7684\u6700\u5c0f\u7a7a\u95f2\u8fde\u63a5\u6570\uff0c\u9ed8\u8ba4\u503c\uff1a1\uff1bRedisson\u5185\u90e8\u7ecf\u5e38\u901a\u8fc7\u53d1\u5e03\u548c\u8ba2\u9605\u6765\u5b9e\u73b0\u8bb8\u591a\u529f\u80fd\u3002 +#\u957f\u671f\u4fdd\u6301\u4e00\u5b9a\u6570\u91cf\u7684\u53d1\u5e03\u8ba2\u9605\u8fde\u63a5\u662f\u5fc5\u987b\u7684 +spring.redisson.subscriptionConnectionMinimumIdleSize=1 +#\u53d1\u5e03\u548c\u8ba2\u9605\u8fde\u63a5\u6c60\u5927\u5c0f\uff0c\u9ed8\u8ba4\u503c\uff1a50 +spring.redisson.subscriptionConnectionPoolSize=50 +#\u8fde\u63a5\u6c60\u6700\u5927\u5bb9\u91cf\u3002\u9ed8\u8ba4\u503c\uff1a64\uff1b\u8fde\u63a5\u6c60\u7684\u8fde\u63a5\u6570\u91cf\u81ea\u52a8\u5f39\u6027\u4f38\u7f29 +spring.redisson.connectionPoolSize=64 +#\u6570\u636e\u5e93\u7f16\u53f7\uff0c\u9ed8\u8ba4\u503c\uff1a0 +spring.redisson.database=0 +#\u662f\u5426\u542f\u7528DNS\u76d1\u6d4b\uff0c\u9ed8\u8ba4\u503c\uff1afalse +spring.redisson.dnsMonitoring=false +#DNS\u76d1\u6d4b\u65f6\u95f4\u95f4\u9694\uff0c\u5355\u4f4d\uff1a\u6beb\u79d2\uff0c\u9ed8\u8ba4\u503c\uff1a5000 +spring.redisson.dnsMonitoringInterval=5000 + + +# elasticsearch +#\u8282\u70b9\u540d\u5b57\uff0c\u9ed8\u8ba4elasticsearch +spring.data.elasticsearch.cluster-name=elasticsearch +# \u8282\u70b9\u5730\u5740\uff0c\u591a\u4e2a\u8282\u70b9\u7528\u9017\u53f7\u9694\u5f00 +spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300 +#spring.data.elasticsearch.local=false +spring.data.elasticsearch.repositories.enable=true + +# ehcache +spring.cache.type=ehcache +spring.cache.ehcache.config=classpath:ehcache.xml \ No newline at end of file diff --git a/bin/main/cassandra.properties b/bin/main/cassandra.properties new file mode 100644 index 0000000..6b39d8e --- /dev/null +++ b/bin/main/cassandra.properties @@ -0,0 +1,3 @@ +cassandra.contactpoints=127.0.0.1 +cassandra.port=9042 +cassandra.keyspace=mydb \ No newline at end of file diff --git a/bin/main/couchdb.xml b/bin/main/couchdb.xml new file mode 100644 index 0000000..e7d752b --- /dev/null +++ b/bin/main/couchdb.xml @@ -0,0 +1,10 @@ + + + + + + \ No newline at end of file diff --git a/bin/main/ehcache.xml b/bin/main/ehcache.xml new file mode 100644 index 0000000..c645ed7 --- /dev/null +++ b/bin/main/ehcache.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/bin/main/log4j2.xml b/bin/main/log4j2.xml new file mode 100644 index 0000000..00314e0 --- /dev/null +++ b/bin/main/log4j2.xml @@ -0,0 +1,61 @@ + + + + + /tmp/logs + /tmp/logs/7z + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/bin/main/xy/SpringBoot2NoSQL/SpringBoot2NoSqlApplication.class b/bin/main/xy/SpringBoot2NoSQL/SpringBoot2NoSqlApplication.class new file mode 100644 index 0000000..55a0c8b Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/SpringBoot2NoSqlApplication.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/config/CassandraConfig.class b/bin/main/xy/SpringBoot2NoSQL/config/CassandraConfig.class new file mode 100644 index 0000000..a428516 Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/config/CassandraConfig.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/config/RedissonConfig.class b/bin/main/xy/SpringBoot2NoSQL/config/RedissonConfig.class new file mode 100644 index 0000000..caf069a Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/config/RedissonConfig.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/controller/Cassandra/CassandraController.class b/bin/main/xy/SpringBoot2NoSQL/controller/Cassandra/CassandraController.class new file mode 100644 index 0000000..6517bc8 Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/controller/Cassandra/CassandraController.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/controller/Ehcache/EhcacheDataController.class b/bin/main/xy/SpringBoot2NoSQL/controller/Ehcache/EhcacheDataController.class new file mode 100644 index 0000000..9f12bb4 Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/controller/Ehcache/EhcacheDataController.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/controller/ElasticSearch/ESDataController.class b/bin/main/xy/SpringBoot2NoSQL/controller/ElasticSearch/ESDataController.class new file mode 100644 index 0000000..e17d887 Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/controller/ElasticSearch/ESDataController.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/controller/ElasticSearch/ESSearchController.class b/bin/main/xy/SpringBoot2NoSQL/controller/ElasticSearch/ESSearchController.class new file mode 100644 index 0000000..64b297e Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/controller/ElasticSearch/ESSearchController.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/controller/Mongo/MongoDataController.class b/bin/main/xy/SpringBoot2NoSQL/controller/Mongo/MongoDataController.class new file mode 100644 index 0000000..a7838b1 Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/controller/Mongo/MongoDataController.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/controller/Redis/RedisDataController.class b/bin/main/xy/SpringBoot2NoSQL/controller/Redis/RedisDataController.class new file mode 100644 index 0000000..0c79dc0 Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/controller/Redis/RedisDataController.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/controller/Redis/RedissonController$1.class b/bin/main/xy/SpringBoot2NoSQL/controller/Redis/RedissonController$1.class new file mode 100644 index 0000000..48bfbb7 Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/controller/Redis/RedissonController$1.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/controller/Redis/RedissonController$2.class b/bin/main/xy/SpringBoot2NoSQL/controller/Redis/RedissonController$2.class new file mode 100644 index 0000000..31b6d52 Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/controller/Redis/RedissonController$2.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/controller/Redis/RedissonController$3.class b/bin/main/xy/SpringBoot2NoSQL/controller/Redis/RedissonController$3.class new file mode 100644 index 0000000..a0763cf Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/controller/Redis/RedissonController$3.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/controller/Redis/RedissonController$4.class b/bin/main/xy/SpringBoot2NoSQL/controller/Redis/RedissonController$4.class new file mode 100644 index 0000000..8239148 Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/controller/Redis/RedissonController$4.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/controller/Redis/RedissonController.class b/bin/main/xy/SpringBoot2NoSQL/controller/Redis/RedissonController.class new file mode 100644 index 0000000..7d40a2f Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/controller/Redis/RedissonController.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/controller/Solr/SolrController.class b/bin/main/xy/SpringBoot2NoSQL/controller/Solr/SolrController.class new file mode 100644 index 0000000..3b52997 Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/controller/Solr/SolrController.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/exception/CreateIndexFailedException.class b/bin/main/xy/SpringBoot2NoSQL/exception/CreateIndexFailedException.class new file mode 100644 index 0000000..e7495eb Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/exception/CreateIndexFailedException.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/exception/GetMappingFailedException.class b/bin/main/xy/SpringBoot2NoSQL/exception/GetMappingFailedException.class new file mode 100644 index 0000000..c7bcf4b Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/exception/GetMappingFailedException.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/exception/IndicesExistsFailedException.class b/bin/main/xy/SpringBoot2NoSQL/exception/IndicesExistsFailedException.class new file mode 100644 index 0000000..e0204f4 Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/exception/IndicesExistsFailedException.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/exception/PutMappingFailedException.class b/bin/main/xy/SpringBoot2NoSQL/exception/PutMappingFailedException.class new file mode 100644 index 0000000..de6de66 Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/exception/PutMappingFailedException.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/model/Cassandra/Customer.class b/bin/main/xy/SpringBoot2NoSQL/model/Cassandra/Customer.class new file mode 100644 index 0000000..67b56fa Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/model/Cassandra/Customer.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/model/ElasticSearch/Product.class b/bin/main/xy/SpringBoot2NoSQL/model/ElasticSearch/Product.class new file mode 100644 index 0000000..200ae1d Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/model/ElasticSearch/Product.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/model/Mongo/Department.class b/bin/main/xy/SpringBoot2NoSQL/model/Mongo/Department.class new file mode 100644 index 0000000..a19a20c Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/model/Mongo/Department.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/model/Mongo/Location.class b/bin/main/xy/SpringBoot2NoSQL/model/Mongo/Location.class new file mode 100644 index 0000000..bca1b0b Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/model/Mongo/Location.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/model/Mongo/Person.class b/bin/main/xy/SpringBoot2NoSQL/model/Mongo/Person.class new file mode 100644 index 0000000..693cf9c Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/model/Mongo/Person.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/model/Redis/User.class b/bin/main/xy/SpringBoot2NoSQL/model/Redis/User.class new file mode 100644 index 0000000..2e25419 Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/model/Redis/User.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/model/Solr/Customer.class b/bin/main/xy/SpringBoot2NoSQL/model/Solr/Customer.class new file mode 100644 index 0000000..dfc695f Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/model/Solr/Customer.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/model/User.class b/bin/main/xy/SpringBoot2NoSQL/model/User.class new file mode 100644 index 0000000..ab078e8 Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/model/User.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/repository/Cassandra/CustomerRepository.class b/bin/main/xy/SpringBoot2NoSQL/repository/Cassandra/CustomerRepository.class new file mode 100644 index 0000000..9a2f9d2 Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/repository/Cassandra/CustomerRepository.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/repository/ElasticSearch/SampleProductRepository.class b/bin/main/xy/SpringBoot2NoSQL/repository/ElasticSearch/SampleProductRepository.class new file mode 100644 index 0000000..e7804c2 Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/repository/ElasticSearch/SampleProductRepository.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/repository/Mongo/DepartmentRepository.class b/bin/main/xy/SpringBoot2NoSQL/repository/Mongo/DepartmentRepository.class new file mode 100644 index 0000000..a712f76 Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/repository/Mongo/DepartmentRepository.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/repository/Mongo/PersonRepository.class b/bin/main/xy/SpringBoot2NoSQL/repository/Mongo/PersonRepository.class new file mode 100644 index 0000000..3a7e037 Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/repository/Mongo/PersonRepository.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/repository/Redis/ObjectRepository.class b/bin/main/xy/SpringBoot2NoSQL/repository/Redis/ObjectRepository.class new file mode 100644 index 0000000..8537515 Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/repository/Redis/ObjectRepository.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/repository/Redis/StringStringRepository.class b/bin/main/xy/SpringBoot2NoSQL/repository/Redis/StringStringRepository.class new file mode 100644 index 0000000..19266cf Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/repository/Redis/StringStringRepository.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/repository/Redis/UserRepository.class b/bin/main/xy/SpringBoot2NoSQL/repository/Redis/UserRepository.class new file mode 100644 index 0000000..f63522d Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/repository/Redis/UserRepository.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/repository/Solr/SolrCustomerRepository.class b/bin/main/xy/SpringBoot2NoSQL/repository/Solr/SolrCustomerRepository.class new file mode 100644 index 0000000..0b8efdb Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/repository/Solr/SolrCustomerRepository.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/service/Ehcache/UserService.class b/bin/main/xy/SpringBoot2NoSQL/service/Ehcache/UserService.class new file mode 100644 index 0000000..dc86cdd Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/service/Ehcache/UserService.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/utils/ESSearchUtil.class b/bin/main/xy/SpringBoot2NoSQL/utils/ESSearchUtil.class new file mode 100644 index 0000000..687e35f Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/utils/ESSearchUtil.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/utils/IElasticSearchMapping.class b/bin/main/xy/SpringBoot2NoSQL/utils/IElasticSearchMapping.class new file mode 100644 index 0000000..8e31fd3 Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/utils/IElasticSearchMapping.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/utils/RandomUtil.class b/bin/main/xy/SpringBoot2NoSQL/utils/RandomUtil.class new file mode 100644 index 0000000..526b58d Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/utils/RandomUtil.class differ diff --git a/bin/main/xy/SpringBoot2NoSQL/utils/RedissonUtil.class b/bin/main/xy/SpringBoot2NoSQL/utils/RedissonUtil.class new file mode 100644 index 0000000..1fd9a17 Binary files /dev/null and b/bin/main/xy/SpringBoot2NoSQL/utils/RedissonUtil.class differ diff --git a/bin/test/xy/SpringBoot2NoSQL/SpringBoot2NoSqlApplicationTests.class b/bin/test/xy/SpringBoot2NoSQL/SpringBoot2NoSqlApplicationTests.class new file mode 100644 index 0000000..e04d345 Binary files /dev/null and b/bin/test/xy/SpringBoot2NoSQL/SpringBoot2NoSqlApplicationTests.class differ diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..1edb447 --- /dev/null +++ b/build.gradle @@ -0,0 +1,49 @@ +buildscript { + ext { + springBootVersion = '2.0.5.RELEASE' + } + repositories { + mavenCentral() + } + dependencies { + classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") + } +} + +apply plugin: 'java' +apply plugin: 'eclipse' +apply plugin: 'org.springframework.boot' +apply plugin: 'io.spring.dependency-management' + +group = 'xy' +version = '0.0.1-SNAPSHOT' +sourceCompatibility = 1.8 + +repositories { + mavenCentral() +} + + +dependencies { + + compile('org.springframework.boot:spring-boot-starter-cache') + compile('org.springframework.boot:spring-boot-starter-data-cassandra') + compile('org.springframework.boot:spring-boot-starter-data-couchbase') + compile('org.springframework.boot:spring-boot-starter-data-elasticsearch') + compile('org.springframework.boot:spring-boot-starter-data-mongodb') + compile('org.springframework.boot:spring-boot-starter-data-neo4j') + compile('org.springframework.boot:spring-boot-starter-data-redis') + compile('org.springframework.boot:spring-boot-starter-data-solr') + + compile group: 'net.sf.ehcache', name: 'ehcache', version: '2.10.5' + compile group: 'org.redisson', name: 'redisson', version: '3.7.5' + //compile group: 'org.springframework.data', name: 'spring-data-hadoop', version: '2.5.0.RELEASE' + + //compile('org.springframework.boot:spring-boot-starter-freemarker') + //compile('org.springframework.boot:spring-boot-starter-thymeleaf') + compile('org.springframework.boot:spring-boot-starter-web') + compile('org.springframework.kafka:spring-kafka') + runtime('org.springframework.boot:spring-boot-devtools') + + testCompile('org.springframework.boot:spring-boot-starter-test') +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..1ce6e58 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..448cc64 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue Feb 06 12:27:20 CET 2018 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-4.8.1-bin.zip diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..4453cce --- /dev/null +++ b/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save ( ) { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..f955316 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/mvnw b/mvnw new file mode 100644 index 0000000..5bf251c --- /dev/null +++ b/mvnw @@ -0,0 +1,225 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Migwn, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +echo $MAVEN_PROJECTBASEDIR +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..019bd74 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,143 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" + +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/myCache.ehcache/users.data b/myCache.ehcache/users.data new file mode 100644 index 0000000..e69de29 diff --git a/myCache.ehcache/users.index b/myCache.ehcache/users.index new file mode 100644 index 0000000..711006c Binary files /dev/null and b/myCache.ehcache/users.index differ diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..25c6c15 --- /dev/null +++ b/pom.xml @@ -0,0 +1,117 @@ + + + 4.0.0 + + xy + SpringBoot2NoSQL + 0.0.1-SNAPSHOT + jar + + SpringBoot2NoSQL + NoSQL for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 2.0.5.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-amqp + + + org.springframework.boot + spring-boot-starter-cache + + + org.springframework.boot + spring-boot-starter-data-cassandra + + + org.springframework.boot + spring-boot-starter-data-couchbase + + + org.springframework.boot + spring-boot-starter-data-elasticsearch + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-data-mongodb + + + org.springframework.boot + spring-boot-starter-data-neo4j + + + org.springframework.boot + spring-boot-starter-data-redis + + + org.springframework.boot + spring-boot-starter-data-solr + + + org.springframework.boot + spring-boot-starter-freemarker + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-starter-web + + + org.mybatis.spring.boot + mybatis-spring-boot-starter + 1.3.2 + + + org.springframework.kafka + spring-kafka + + + + org.springframework.boot + spring-boot-devtools + runtime + + + mysql + mysql-connector-java + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..531f3fb --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'SpringBoot2NoSQL' diff --git a/src/main/java/xy/SpringBoot2NoSQL/SpringBoot2NoSqlApplication.java b/src/main/java/xy/SpringBoot2NoSQL/SpringBoot2NoSqlApplication.java new file mode 100644 index 0000000..0b916bf --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/SpringBoot2NoSqlApplication.java @@ -0,0 +1,17 @@ +package xy.SpringBoot2NoSQL; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.scheduling.annotation.EnableScheduling; + +@EnableCaching +@EnableScheduling +@SpringBootApplication +public class SpringBoot2NoSqlApplication { + + public static void main(String[] args) { + System.setProperty("es.set.netty.runtime.available.processors", "false"); + SpringApplication.run(SpringBoot2NoSqlApplication.class, args); + } +} diff --git a/src/main/java/xy/SpringBoot2NoSQL/config/CassandraConfig.java b/src/main/java/xy/SpringBoot2NoSQL/config/CassandraConfig.java new file mode 100644 index 0000000..78f601b --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/config/CassandraConfig.java @@ -0,0 +1,45 @@ +package xy.SpringBoot2NoSQL.config; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.data.cassandra.config.AbstractCassandraConfiguration; +import org.springframework.data.cassandra.config.CassandraClusterFactoryBean; +import org.springframework.data.cassandra.core.mapping.BasicCassandraMappingContext; +import org.springframework.data.cassandra.core.mapping.CassandraMappingContext; +import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories; + +@Configuration +@PropertySource(value = { "classpath:cassandra.properties" }) +@EnableCassandraRepositories(basePackages = "xy.SpringBoot2NoSQL.repository.Cassandra") +public class CassandraConfig extends AbstractCassandraConfiguration { + private static final Log LOGGER = LogFactory.getLog(CassandraConfig.class); + + @Autowired + private Environment environment; + + @Override + protected String getKeyspaceName() { + return environment.getProperty("cassandra.keyspace"); + } + + @Override + @Bean + public CassandraClusterFactoryBean cluster() { + final CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean(); + cluster.setContactPoints(environment.getProperty("cassandra.contactpoints")); + cluster.setPort(Integer.parseInt(environment.getProperty("cassandra.port"))); + LOGGER.info("Cluster created with contact points [" + environment.getProperty("cassandra.contactpoints") + "] " + "& port [" + Integer.parseInt(environment.getProperty("cassandra.port")) + "]."); + return cluster; + } + + @Override + @Bean + public CassandraMappingContext cassandraMapping() throws ClassNotFoundException { + return new BasicCassandraMappingContext(); + } +} \ No newline at end of file diff --git a/src/main/java/xy/SpringBoot2NoSQL/config/RedissonConfig.java b/src/main/java/xy/SpringBoot2NoSQL/config/RedissonConfig.java new file mode 100644 index 0000000..63ea866 --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/config/RedissonConfig.java @@ -0,0 +1,263 @@ +package xy.SpringBoot2NoSQL.config; + +import org.redisson.Redisson; +import org.redisson.api.RedissonClient; +import org.redisson.client.codec.Codec; +import org.redisson.config.Config; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.util.ClassUtils; + +import io.netty.channel.nio.NioEventLoopGroup; + +/** + * redisson 客户端配置,而不是使用spring data redis + * 这里配置连接的模式是单机模式,如想配置集群模式和哨兵模式,请参考官方wiki + * https://github.com/redisson/redisson/wiki/ + */ +@ConfigurationProperties(prefix = "spring.redisson") +@Configuration +public class RedissonConfig{ + + private String address; + private int connectionMinimumIdleSize = 10; + private int idleConnectionTimeout=10000; + private int pingTimeout=1000; + private int connectTimeout=10000; + private int timeout=3000; + private int retryAttempts=3; + private int retryInterval=1500; + private int reconnectionTimeout=3000; + private int failedAttempts=3; + private String password = null; + private int subscriptionsPerConnection=5; + private String clientName=null; + private int subscriptionConnectionMinimumIdleSize = 1; + private int subscriptionConnectionPoolSize = 50; + private int connectionPoolSize = 64; + private int database = 0; + private boolean dnsMonitoring = false; + private int dnsMonitoringInterval = 5000; + + private int thread; //当前处理核数量 * 2 + + private String codec="org.redisson.codec.JsonJacksonCodec"; + + @Bean(destroyMethod = "shutdown") + @ConditionalOnProperty(name="spring.redisson.address") + RedissonClient redisson() throws Exception { + Config config = new Config(); + config.useSingleServer().setAddress(address) + .setConnectionMinimumIdleSize(connectionMinimumIdleSize) + .setConnectionPoolSize(connectionPoolSize) + .setDatabase(database) + .setDnsMonitoringInterval(dnsMonitoringInterval) + .setSubscriptionConnectionMinimumIdleSize(subscriptionConnectionMinimumIdleSize) + .setSubscriptionConnectionPoolSize(subscriptionConnectionPoolSize) + .setSubscriptionsPerConnection(subscriptionsPerConnection) + .setClientName(clientName) + .setRetryAttempts(retryAttempts) + .setRetryInterval(retryInterval) + .setTimeout(timeout) + .setConnectTimeout(connectTimeout) + .setIdleConnectionTimeout(idleConnectionTimeout) + .setPingTimeout(pingTimeout) + .setPassword(password); + Codec codec=(Codec)ClassUtils.forName(getCodec(),ClassUtils.getDefaultClassLoader()).newInstance(); + config.setCodec(codec); + config.setThreads(thread); + config.setEventLoopGroup(new NioEventLoopGroup()); + return Redisson.create(config); + } + + /** + * 哨兵模式自动装配 + * @return + */ +// @Bean +// @ConditionalOnProperty(name="redisson.master-name") +// RedissonClient redissonSentinel() { +// Config config = new Config(); +// SentinelServersConfig serverConfig = config.useSentinelServers().addSentinelAddress(redssionProperties.getSentinelAddresses()) +// .setMasterName(redssionProperties.getMasterName()) +// .setTimeout(redssionProperties.getTimeout()) +// .setMasterConnectionPoolSize(redssionProperties.getMasterConnectionPoolSize()) +// .setSlaveConnectionPoolSize(redssionProperties.getSlaveConnectionPoolSize()); +// +// if(StringUtils.isNotBlank(redssionProperties.getPassword())) { +// serverConfig.setPassword(redssionProperties.getPassword()); +// } +// return Redisson.create(config); +// } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public int getConnectionMinimumIdleSize() { + return connectionMinimumIdleSize; + } + + public void setConnectionMinimumIdleSize(int connectionMinimumIdleSize) { + this.connectionMinimumIdleSize = connectionMinimumIdleSize; + } + + public int getIdleConnectionTimeout() { + return idleConnectionTimeout; + } + + public void setIdleConnectionTimeout(int idleConnectionTimeout) { + this.idleConnectionTimeout = idleConnectionTimeout; + } + + public int getPingTimeout() { + return pingTimeout; + } + + public void setPingTimeout(int pingTimeout) { + this.pingTimeout = pingTimeout; + } + + public int getConnectTimeout() { + return connectTimeout; + } + + public void setConnectTimeout(int connectTimeout) { + this.connectTimeout = connectTimeout; + } + + public int getTimeout() { + return timeout; + } + + public void setTimeout(int timeout) { + this.timeout = timeout; + } + + public int getRetryAttempts() { + return retryAttempts; + } + + public void setRetryAttempts(int retryAttempts) { + this.retryAttempts = retryAttempts; + } + + public int getRetryInterval() { + return retryInterval; + } + + public void setRetryInterval(int retryInterval) { + this.retryInterval = retryInterval; + } + + public int getReconnectionTimeout() { + return reconnectionTimeout; + } + + public void setReconnectionTimeout(int reconnectionTimeout) { + this.reconnectionTimeout = reconnectionTimeout; + } + + public int getFailedAttempts() { + return failedAttempts; + } + + public void setFailedAttempts(int failedAttempts) { + this.failedAttempts = failedAttempts; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public int getSubscriptionsPerConnection() { + return subscriptionsPerConnection; + } + + public void setSubscriptionsPerConnection(int subscriptionsPerConnection) { + this.subscriptionsPerConnection = subscriptionsPerConnection; + } + + public String getClientName() { + return clientName; + } + + public void setClientName(String clientName) { + this.clientName = clientName; + } + + public int getSubscriptionConnectionMinimumIdleSize() { + return subscriptionConnectionMinimumIdleSize; + } + + public void setSubscriptionConnectionMinimumIdleSize(int subscriptionConnectionMinimumIdleSize) { + this.subscriptionConnectionMinimumIdleSize = subscriptionConnectionMinimumIdleSize; + } + + public int getSubscriptionConnectionPoolSize() { + return subscriptionConnectionPoolSize; + } + + public void setSubscriptionConnectionPoolSize(int subscriptionConnectionPoolSize) { + this.subscriptionConnectionPoolSize = subscriptionConnectionPoolSize; + } + + public int getConnectionPoolSize() { + return connectionPoolSize; + } + + public void setConnectionPoolSize(int connectionPoolSize) { + this.connectionPoolSize = connectionPoolSize; + } + + public int getDatabase() { + return database; + } + + public void setDatabase(int database) { + this.database = database; + } + + public boolean isDnsMonitoring() { + return dnsMonitoring; + } + + public void setDnsMonitoring(boolean dnsMonitoring) { + this.dnsMonitoring = dnsMonitoring; + } + + public int getDnsMonitoringInterval() { + return dnsMonitoringInterval; + } + + public void setDnsMonitoringInterval(int dnsMonitoringInterval) { + this.dnsMonitoringInterval = dnsMonitoringInterval; + } + + public int getThread() { + return thread; + } + + public void setThread(int thread) { + this.thread = thread; + } + + public String getCodec() { + return codec; + } + + public void setCodec(String codec) { + this.codec = codec; + } + +} diff --git a/src/main/java/xy/SpringBoot2NoSQL/controller/Cassandra/CassandraController.java b/src/main/java/xy/SpringBoot2NoSQL/controller/Cassandra/CassandraController.java new file mode 100644 index 0000000..848d389 --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/controller/Cassandra/CassandraController.java @@ -0,0 +1,76 @@ +package xy.SpringBoot2NoSQL.controller.Cassandra; + +import java.util.List; +import java.util.Optional; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import xy.SpringBoot2NoSQL.model.Cassandra.Customer; +import xy.SpringBoot2NoSQL.repository.Cassandra.CustomerRepository; + + + +@RestController +@RequestMapping("/cassandra") +public class CassandraController { + + Logger logger = LogManager.getLogger(getClass()); + + @Autowired + CustomerRepository customerRepository; + + @RequestMapping("/add") + public String add(){ + customerRepository.deleteAll(); + + Customer cust_1 = new Customer("Test1", "Test1", "Test1", 20); + Customer cust_2 = new Customer("Test2", "Test2", "Test2", 25); + Customer cust_3 = new Customer("Test3", "Test3", "Test3", 30); + Customer cust_4 = new Customer("Test4", "Test4", "Test4", 35); + Customer cust_5 = new Customer("Test5", "Test5", "Test5", 40); + Customer cust_6 = new Customer("Test6", "Test6", "Test6", 45); + + customerRepository.save(cust_1); + customerRepository.save(cust_2); + customerRepository.save(cust_3); + customerRepository.save(cust_4); + customerRepository.save(cust_5); + customerRepository.save(cust_6); + + return "ok"; + } + + + @RequestMapping("/all") + public Iterable getAll(){ + + return customerRepository.findAll(); + } + + @RequestMapping("/getByID/{id}") + public Optional getByID(@PathVariable("id") String id){ + + return customerRepository.findById(id); + } + + @RequestMapping("/getByName/{name}") + public List getByName(@PathVariable("name") String name){ + + return customerRepository.findByLastname(name); + + } + + @RequestMapping("/getByAge/{age}") + public List getByAge(@PathVariable("age") String age){ + + return customerRepository.findByAgeGreaterThan(Integer.valueOf(age)); + + } + + +} diff --git a/src/main/java/xy/SpringBoot2NoSQL/controller/Couchbase/CouchbaseController.java b/src/main/java/xy/SpringBoot2NoSQL/controller/Couchbase/CouchbaseController.java new file mode 100644 index 0000000..676c2b9 --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/controller/Couchbase/CouchbaseController.java @@ -0,0 +1,53 @@ +//package xy.SpringBoot2NoSQL.controller.Couchbase; +// +//import java.util.Arrays; +//import java.util.List; +//import java.util.Optional; +// +//import org.springframework.beans.factory.annotation.Autowired; +//import org.springframework.web.bind.annotation.PathVariable; +//import org.springframework.web.bind.annotation.RequestMapping; +//import org.springframework.web.bind.annotation.RestController; +// +//import xy.SpringBoot2NoSQL.model.Couchbase.Customer; +//import xy.SpringBoot2NoSQL.repository.Couchbase.CouchbaseCustomerRepository; +// +//@RestController +//@RequestMapping("/couchbase") +//public class CouchbaseController { +// +// @Autowired +// CouchbaseCustomerRepository couchbaseCustomerRepository; +// +// @RequestMapping("/add") +// public String add(){ +// +// couchbaseCustomerRepository.deleteAll(); +// couchbaseCustomerRepository.saveAll(Arrays.asList(new Customer("01", "Jack", "Smith"), +// new Customer("02", "Adam", "Johnson"), +// new Customer("03", "Kim", "Smith"), +// new Customer("04", "David", "Williams"), +// new Customer("05", "Peter", "Davis"))); +// +// return "ok"; +// } +// +// @RequestMapping("/all") +// public Iterable getAll(){ +// +// return couchbaseCustomerRepository.findAll(); +// } +// +// @RequestMapping("/getByID/{id}") +// public Optional getByID(@PathVariable("id") String id){ +// +// return couchbaseCustomerRepository.findById(id); +// } +// +// @RequestMapping("/findByLastName/{name}") +// public List findByLastName(@PathVariable("name") String name){ +// +// return couchbaseCustomerRepository.findByLastName(name); +// } +// +//} diff --git a/src/main/java/xy/SpringBoot2NoSQL/controller/Ehcache/EhcacheDataController.java b/src/main/java/xy/SpringBoot2NoSQL/controller/Ehcache/EhcacheDataController.java new file mode 100644 index 0000000..43544bb --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/controller/Ehcache/EhcacheDataController.java @@ -0,0 +1,64 @@ +package xy.SpringBoot2NoSQL.controller.Ehcache; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import net.sf.ehcache.CacheManager; +import xy.SpringBoot2NoSQL.model.User; +import xy.SpringBoot2NoSQL.service.Ehcache.UserService; + +@RestController +@RequestMapping("/ehcache") +public class EhcacheDataController { + + Logger logger = LogManager.getLogger(getClass()); + + @Autowired + UserService userService; + + @Autowired + private CacheManager cacheManager; + + /** + * 创建100个测试用户 + * @return + */ + @RequestMapping("/users") + public List getUsers(){ + + logger.info("using cache manager: " + cacheManager.getClass().getName()); + + userService.clearCache(); + + //新建对象 + List users = new ArrayList(); + for (int i=0;i<100;i++){ + users.add(userService.getUser("test"+i)); + } + + for (int i=0;i<100;i++){ + //测试获取对象是否是经过缓存 + userService.getUser("test"+i); + } + + return users; + } + + /** + * 获取测试用户,看看是否经过缓存 + * @return + */ + @RequestMapping("/user/{name}") + public User getUser(@PathVariable("name") String name){ + return userService.getUser(name); + + } + +} diff --git a/src/main/java/xy/SpringBoot2NoSQL/controller/ElasticSearch/ESDataController.java b/src/main/java/xy/SpringBoot2NoSQL/controller/ElasticSearch/ESDataController.java new file mode 100644 index 0000000..5a71565 --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/controller/ElasticSearch/ESDataController.java @@ -0,0 +1,186 @@ +package xy.SpringBoot2NoSQL.controller.ElasticSearch; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.elasticsearch.action.ActionFuture; +import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest; +import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; +import org.elasticsearch.client.Client; +import org.elasticsearch.cluster.health.ClusterHealthStatus; +import org.elasticsearch.index.query.BoolQueryBuilder; +import org.elasticsearch.index.query.QueryBuilders; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.elasticsearch.core.ElasticsearchOperations; +import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; +import org.springframework.data.elasticsearch.core.query.DeleteQuery; +import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; +import org.springframework.data.elasticsearch.core.query.SearchQuery; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import xy.SpringBoot2NoSQL.model.ElasticSearch.Product; +import xy.SpringBoot2NoSQL.repository.ElasticSearch.SampleProductRepository; + +@RestController +@RequestMapping("/es") +public class ESDataController { + + @Autowired + private ElasticsearchOperations elasticsearchOperations; + + @Autowired + SampleProductRepository sampleProductRepository; + + @Autowired + private ElasticsearchTemplate elasticsearchTemplate; + + //服务情况查询 + @GetMapping("details") + public ResponseEntity> getElasticInformation() { + + Client client = elasticsearchOperations.getClient(); + Map asMap = client.settings().getAsMap(); + return ResponseEntity.ok(asMap); + } + + //健康检查 + @GetMapping("checkHealth") + public String checkHealth() { + + return getHealth(); + } + + @GetMapping("insertProduct") + public Product insert() { + Product product = new Product("1", "测试产品1", "测试产品111111.", true); + return sampleProductRepository.save(product); + } + + @GetMapping("insertProductMore") + public String insertProductMore() { + + List productList = new ArrayList(); + + for (int i = 0; i < 100; i++) { + Product product = new Product(String.valueOf(i), "测试产品" + i, "测试产品描述.", true); + productList.add(product); + } + + // 只需要执行一次批量 + sampleProductRepository.saveAll(productList); + + return "success"; + } + + @GetMapping("insertProduct2/{id}/{name}") + public Product insert2(@PathVariable String name, @PathVariable String id) { + Product product = new Product(id, name, name + "产品描述.", true); + return sampleProductRepository.save(product); + } + + @GetMapping("findByNameProducts/{name}") + public List findByNameProducts(@PathVariable String name) { + List list = sampleProductRepository.findByName(name); + return list; + } + + @GetMapping("findByNameAndIdProducts/{name}/{id}") + public List findByNameAndIdProducts(@PathVariable String name, @PathVariable String id) { + List list = sampleProductRepository.findByNameAndId(name, id); + return list; + } + + @GetMapping("findByNameProductsPage/{name}/{page}/{size}") + public List findByNameProductsPage(@PathVariable String name, @PathVariable int page, + @PathVariable int size) { + List list = sampleProductRepository.findByName(name, PageRequest.of(page, size)); + return list; + } + + @GetMapping("count") + public long CountAllElementsInIndex() { + + long count = sampleProductRepository.count(); + return count; + } + + @GetMapping("searchQueries/{id}/{name}/{page}/{size}") + public Page SearchQueries(@PathVariable String name, @PathVariable String id, @PathVariable int page, + @PathVariable int size) { + + BoolQueryBuilder bqb = QueryBuilders.boolQuery(); + bqb.must(QueryBuilders.termQuery("name", name)); + //bqb.must(QueryBuilders.rangeQuery("id").gt(id));// 大于 + + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(bqb).withPageable(PageRequest.of(page, size)) + .build(); + + Page products = sampleProductRepository.search(searchQuery); + return products; + } + + //根据id删除 + public boolean deleteById(String id) { + try { + elasticsearchTemplate.delete(getEntityClass(), id); + return true; + } catch (Exception e) { + return false; + } + } + + //根据条件删除 + public boolean deleteByQuery(Map filedContentMap) { + try { + DeleteQuery dq = new DeleteQuery(); + + BoolQueryBuilder query=QueryBuilders. boolQuery(); + if(filedContentMap!=null) + for (String key : filedContentMap.keySet()) {//字段查询 + query.must(QueryBuilders.matchQuery(key,filedContentMap.get(key))); + } + dq.setQuery(query); + elasticsearchTemplate.delete(dq, getEntityClass()); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + + + //健康检查 + public String getHealth() { + try { + Client client = elasticsearchOperations.getClient(); + ActionFuture health = client.admin() + .cluster().health(new ClusterHealthRequest()); + ClusterHealthStatus status = health.actionGet().getStatus(); + if (status.value() == ClusterHealthStatus.RED.value()) { + return "red"; + } + if (status.value() == ClusterHealthStatus.GREEN.value()) { + return "green"; + } + if (status.value() == ClusterHealthStatus.YELLOW.value()) { + return "yellow"; + } + return "unknow"; + } catch (Exception e) { + + return "unknow"; + } + } + + private Class getEntityClass() { + + return Product.class; + } +} diff --git a/src/main/java/xy/SpringBoot2NoSQL/controller/ElasticSearch/ESSearchController.java b/src/main/java/xy/SpringBoot2NoSQL/controller/ElasticSearch/ESSearchController.java new file mode 100644 index 0000000..2e6eaeb --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/controller/ElasticSearch/ESSearchController.java @@ -0,0 +1,67 @@ +package xy.SpringBoot2NoSQL.controller.ElasticSearch; + +import org.elasticsearch.index.query.QueryBuilder; +import org.elasticsearch.index.query.QueryBuilders; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import xy.SpringBoot2NoSQL.model.ElasticSearch.Product; +import xy.SpringBoot2NoSQL.repository.ElasticSearch.SampleProductRepository; +import xy.SpringBoot2NoSQL.utils.ESSearchUtil; + +@RestController +@RequestMapping("/essearch") +public class ESSearchController { + + @Autowired + SampleProductRepository sampleProductRepository; + + @GetMapping("search") + public Page search() { + + return sampleProductRepository.search(getBoolQuery(), PageRequest.of(0, 5)); + } + + @GetMapping("searchAll/{page}") + public Page searchAll(@PathVariable int page) { + + return sampleProductRepository.search(ESSearchUtil.matchAllQuery(), PageRequest.of(page, 5)); + } + + @GetMapping("searchProduct/{key}/{value}/{searchtype}") + public Page searchProduct(@PathVariable String key,@PathVariable String value, @PathVariable String searchtype) { + Page products = null; + + if (searchtype.equals("matchQuery")) { + products = sampleProductRepository.search(ESSearchUtil.matchQuery(key, value), PageRequest.of(0, 5)); + } + + if (searchtype.equals("matchPhraseQuery")) { + products = sampleProductRepository.search(ESSearchUtil.matchPhraseQuery(key, value), PageRequest.of(0, 5)); + } + + if (searchtype.equals("fuzzyQuery")) { + products = sampleProductRepository.search(ESSearchUtil.fuzzyQuery(key, value), PageRequest.of(0, 5)); + } + + if (searchtype.equals("termsQuery")) { + products = sampleProductRepository.search(ESSearchUtil.termsQuery(key, value), PageRequest.of(0, 5)); + } + + return products; + } + + public QueryBuilder getBoolQuery() { + + return QueryBuilders.boolQuery() + .must(QueryBuilders.matchPhraseQuery("name", "测试产品1")) + //.mustNot(QueryBuilders.termQuery("enabled", true)); + .must(QueryBuilders.matchPhraseQuery("enabled", true)); + } + +} diff --git a/src/main/java/xy/SpringBoot2NoSQL/controller/Mongo/MongoDataController.java b/src/main/java/xy/SpringBoot2NoSQL/controller/Mongo/MongoDataController.java new file mode 100644 index 0000000..e9e9c4e --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/controller/Mongo/MongoDataController.java @@ -0,0 +1,110 @@ +package xy.SpringBoot2NoSQL.controller.Mongo; + + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import xy.SpringBoot2NoSQL.model.Mongo.Department; +import xy.SpringBoot2NoSQL.model.Mongo.Location; +import xy.SpringBoot2NoSQL.model.Mongo.Person; +import xy.SpringBoot2NoSQL.repository.Mongo.DepartmentRepository; +import xy.SpringBoot2NoSQL.repository.Mongo.PersonRepository; + +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Optional; + +@RestController +@RequestMapping("/mongo") +public class MongoDataController { + + @Autowired + PersonRepository personRepository; + @Autowired + DepartmentRepository departmentRepository; + + @RequestMapping("/persons/{name}") + public Person getPerson(@PathVariable("name") String name){ + return personRepository.findByName(name); + } + + @GetMapping("findAll") + public List getUserList() { + List userInfoList = personRepository.findAll(); + return userInfoList; + } + + @GetMapping("query1") + public Person q1(String name){ + return personRepository.findByName(name); + } + + @GetMapping("query2") + public List q2(Integer age){ + return personRepository.withQueryFindByAge(age); + } + + @GetMapping("delete") + public String delete(String id) { + personRepository.deleteById(id); + return "success"; + } + + @DeleteMapping("/colleagues/{name}") + public ResponseEntity deleteColleague(@PathVariable String name){ + Person person = personRepository.findByName(name); + if(person!=null) { + personRepository.delete(person); + return new ResponseEntity<>(HttpStatus.ACCEPTED); + } + return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + } + + @GetMapping("insert") + public Person insert(Long id, String username, String password) { + Person user = new Person("test2",22); + return personRepository.insert(user); + } + + //要先执行添加部门的操作 + @RequestMapping("saveDepartment") + public Department saveDepartment(){ + Department d = new Department("abc001","研发部"); + return departmentRepository.save(d); + } + + //执行这个之前要先执行”saveDepartment“,因为需要一个部门的引用 + @RequestMapping("save") + public Person save(){ + Person p = new Person("王昕",32); + Collection locations = new LinkedHashSet(); + Location loc1 = new Location("上海","2009"); + Location loc2 = new Location("广州","2011"); + locations.add(loc1); + locations.add(loc2); + + p.setLocations(locations); + + Department d = departmentRepository.findByName("研发部"); + p.setDepartment(d); + + return personRepository.save(p); + } + + + @PostMapping("/formsave") + public ResponseEntity addColleague(@RequestBody Person person){ + personRepository.save(person); + return new ResponseEntity<>(HttpStatus.CREATED); + } + +} \ No newline at end of file diff --git a/src/main/java/xy/SpringBoot2NoSQL/controller/Redis/RedisDataController.java b/src/main/java/xy/SpringBoot2NoSQL/controller/Redis/RedisDataController.java new file mode 100644 index 0000000..1343cf3 --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/controller/Redis/RedisDataController.java @@ -0,0 +1,34 @@ +package xy.SpringBoot2NoSQL.controller.Redis; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import xy.SpringBoot2NoSQL.model.Redis.User; +import xy.SpringBoot2NoSQL.repository.Redis.ObjectRepository; +import xy.SpringBoot2NoSQL.repository.Redis.StringStringRepository; +import xy.SpringBoot2NoSQL.repository.Redis.UserRepository; + +@RestController +@RequestMapping("/redis") +public class RedisDataController { + + @Autowired + ObjectRepository objRepository; + @Autowired + StringStringRepository stringStringRepository; + + @RequestMapping("/add/{name}") + public String getRecognition(@PathVariable("name") String name){ + User user = new User(name,name); + objRepository.save(user); + + return "add success."; + } + + @RequestMapping("/user/{name}") + public User getUser(@PathVariable("name") String name){ + return (User)objRepository.get(name); + + } +} diff --git a/src/main/java/xy/SpringBoot2NoSQL/controller/Redis/RedissonController.java b/src/main/java/xy/SpringBoot2NoSQL/controller/Redis/RedissonController.java new file mode 100644 index 0000000..110be44 --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/controller/Redis/RedissonController.java @@ -0,0 +1,329 @@ +package xy.SpringBoot2NoSQL.controller.Redis; + +import java.util.concurrent.TimeUnit; + +import org.redisson.Redisson; +import org.redisson.api.BatchOptions; +import org.redisson.api.BatchResult; +import org.redisson.api.LocalCachedMapOptions; +import org.redisson.api.RAtomicDouble; +import org.redisson.api.RBatch; +import org.redisson.api.RBloomFilter; +import org.redisson.api.RBoundedBlockingQueue; +import org.redisson.api.RBucket; +import org.redisson.api.RHyperLogLog; +import org.redisson.api.RLocalCachedMap; +import org.redisson.api.RLongAdder; +import org.redisson.api.RMapCache; +import org.redisson.api.RScoredSortedSet; +import org.redisson.api.RedissonClient; +import org.redisson.api.TransactionOptions; +import org.redisson.api.map.event.EntryCreatedListener; +import org.redisson.api.map.event.EntryEvent; +import org.redisson.api.map.event.EntryExpiredListener; +import org.redisson.api.map.event.EntryRemovedListener; +import org.redisson.api.map.event.EntryUpdatedListener; +import org.redisson.config.Config; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import io.netty.util.concurrent.Future; +import xy.SpringBoot2NoSQL.config.RedissonConfig; +import xy.SpringBoot2NoSQL.model.Redis.User; +import xy.SpringBoot2NoSQL.utils.RedissonUtil; + + +@RestController +@RequestMapping("/redisson") +public class RedissonController { + + // 单Redis节点模式,默认连接地址 127.0.0.1:6379 + RedissonClient redisson = Redisson.create(); + + + /** + * Map 获取 + * @param name + * @param key + * @return + */ + @RequestMapping("/getMap/{name}/{key}") + public String get(@PathVariable("name") String name,@PathVariable("key") String key){ + + String result = (String) redisson.getMap(name).get(key); + + return result; + } + + /** + * 本地缓存(Local Cache)也叫就近缓存(Near Cache)。 + * 这类映射的使用主要用于在特定的场景下,映射缓存(MapCache)上的高度频繁的读取操作, + * 使网络通信都被视为瓶颈的情况。Redisson与Redis通信的同时,还将部分数据保存在本地内存里。这样的设计的好处是它能将读取速度提高最多 45倍 + * @param name + * @param key + * @return + */ + @RequestMapping("/getLocalCachedMap/{name}/{key}") + public String getLocalCachedMap(@PathVariable("name") String name,@PathVariable("key") String key){ + + LocalCachedMapOptions options = LocalCachedMapOptions.defaults() + .evictionPolicy(LocalCachedMapOptions.EvictionPolicy.LFU) + .cacheSize(100) + .syncStrategy(LocalCachedMapOptions.SyncStrategy.UPDATE) //同步缓存 + .timeToLive(10, TimeUnit.SECONDS) + .maxIdle(10, TimeUnit.SECONDS); + + RLocalCachedMap map = redisson.getLocalCachedMap(name,options); + + map.put(key, "测试值"); + + String result = (String)map.get(key); + + return result; + } + + /** + * 元素淘汰功能(Eviction)和事件监听 + * 带有元素淘汰(Eviction)机制的映射类允许针对一个映射中每个元素单独设定 有效时间 和 最长闲置时间 。 + * @param name + * @param key + * @return + */ + @RequestMapping("/getMapCache/{name}/{key}") + public int getMapCache(@PathVariable("name") String name,@PathVariable("key") String key){ + + RMapCache map = redisson.getMapCache(name); + //LRU有界映射设置 + // 将该映射的最大容量限制设定或更改为10 + map.setMaxSize(10); + + map.put(key, 999); + map.put(key+"_TimeTtoLive", 888, 1, TimeUnit.SECONDS);//有效时间1秒 + + int updateListener = map.addListener(new EntryUpdatedListener() { + @Override + public void onUpdated(EntryEvent event) { +// event.getKey(); // 字段名 +// event.getValue(); // 新值 +// event.getOldValue(); // 旧值 + } + }); + + int createListener = map.addListener(new EntryCreatedListener() { + @Override + public void onCreated(EntryEvent event) { +// event.getKey(); // 字段名 +// event.getValue(); // 值 + } + }); + + int expireListener = map.addListener(new EntryExpiredListener() { + @Override + public void onExpired(EntryEvent event) { +// event.getKey(); // 字段名 +// event.getValue(); // 值 + + } + }); + + int removeListener = map.addListener(new EntryRemovedListener() { + @Override + public void onRemoved(EntryEvent event) { +// event.getKey(); // 字段名 +// event.getValue(); // 值 + } + }); + + map.removeListener(updateListener); + map.removeListener(createListener); + map.removeListener(expireListener); + map.removeListener(removeListener); + try { + Thread.sleep(200);//如果改成1000以上,则无法取出映射的值,因为已删除 + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + int result = map.get(key+"_TimeTtoLive"); + return result; + } + + + /** + * 设置分布式对象桶(Object Bucket) + * @param key + * @param name + * @param value + * @return + */ + @RequestMapping("/setObjectBucket/{key}") + public String setObjectBucket(@PathVariable("key") String key){ + + RBucket bucket = redisson.getBucket(key); + bucket.set(new User("wangxin","王昕")); + + return "objectBucket set success."; + } + + @RequestMapping("/getBucket/{key}") + public User getBucket(@PathVariable("key") String key){ + + User user = (User) RedissonUtil.getRBucket(redisson, key).get(); + + return user; + } + + + /** + * 分布式基数估计算法 + * @param key + * @return + */ + @RequestMapping("/hyperLogLog/{key}") + public Long hyperLogLog(@PathVariable("key") String key){ + + RHyperLogLog log = redisson.getHyperLogLog(key); + + log.add(1); + log.add(2); + log.add(3); + + Long count =log.count(); + + return count; + } + + + /** + * 分布式整长型累加器 + * 基于Redis的Redisson分布式整长型累加器采用了与java.util.concurrent.atomic.LongAdder类似的接口。 + * 通过利用客户端内置的LongAdder对象,为分布式环境下递增和递减操作提供了很高得性能。 + * 据统计其性能最高比分布式AtomicLong对象快 12000 倍。完美适用于分布式统计计量场景。 + * @param key + * @return + */ + @RequestMapping("/longAdder/{key}") + public Long longAdder(@PathVariable("key") String key){ + + RLongAdder atomicLong = redisson.getLongAdder(key); + atomicLong.add(12); + atomicLong.increment(); + atomicLong.increment(); + atomicLong.decrement(); + + Long count =atomicLong.sum(); + + return count; + } + + /** + * 分布式原子双精度浮点 + * 分布式原子双精度浮点RAtomicDouble,弥补了Java自身的不足 + * @param key + * @return + */ + @RequestMapping("/atomicDouble/{key}") + public double atomicDouble(@PathVariable("key") String key){ + + RAtomicDouble atomicDouble = redisson.getAtomicDouble(key); + atomicDouble.set(123.11); + atomicDouble.addAndGet(4.25); + + double value = atomicDouble.get(); + + return value; + } + + /** + * 异步批量执行 + * @param key + * @return + */ + @RequestMapping("/batch") + public String batch(){ + + RBatch batch = redisson.createBatch(BatchOptions.defaults()); + //RTransaction RTransaction = redisson.createTransaction(TransactionOptions.defaults()) + batch.getMap("test").fastPutAsync("1", "2"); + batch.getMap("test").fastPutAsync("2", "3"); + batch.getMap("test").putAsync("2", "新的值"); + + // 将写入操作同步到从节点 + // 同步到2个从节点,等待时间为1秒钟 + //batch.syncSlaves(2, 1, TimeUnit.SECONDS); + + BatchResult res = batch.execute(); + + return res.getResponses().toString(); + } + + + + /** + * 计分排序集(ScoredSortedSet) + * @return + */ + @RequestMapping("/scoredSortedSet") + public String ScoredSortedSet(){ + + RScoredSortedSet set = redisson.getScoredSortedSet("scoredSortedSet"); + set.clear(); + + set.add(3.13, new User("Tom","Tom name")); + set.addAsync(0.123, new User("Dog","Dog name")); + + User user = new User("Cat","Cat name"); + set.add(4.67, user); + set.addScore(user, 0.1); //加分 + + int index = set.rank(user); // 获取元素在集合中的位置 + + Double score = set.getScore(user); // 获取元素的评分 + + return "位置:"+index +",分数:"+score; + } + + + /** + * 有界阻塞队列(Bounded Blocking Queue) + * @return + */ + @RequestMapping("/boundedBlockingQueue") + public String BoundedBlockingQueue(){ + + RBoundedBlockingQueue queue = redisson.getBoundedBlockingQueue("anyQueue"); + queue.clear(); + // 如果初始容量(边界)设定成功则返回`真(true)`, + // 如果初始容量(边界)已近存在则返回`假(false)`。 + queue.trySetCapacity(2); + + queue.offer(new User("Tom","Tom name")); + queue.offer(new User("Cat","Cat name")); + //此时容量已满,add方法会直接阻塞 + //queue.add(new User("Cat2","Cat2 name")); + // 此时容量已满,下面代码将会被阻塞,直到有空闲为止。 + try { + queue.put(new User("Dog","Dog name")); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + User obj = queue.peek();//获取队列第一个元素,但并不从队列中删除 + User obj2 = null; + try { + obj2 = queue.poll(3, TimeUnit.SECONDS);//获取队列第一个元素,并删除 + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + User obj3 = queue.poll(); + return obj.getLogin() +","+ obj2.getLogin()+","+ obj3.getLogin(); + } + + + +} diff --git a/src/main/java/xy/SpringBoot2NoSQL/controller/Solr/SolrController.java b/src/main/java/xy/SpringBoot2NoSQL/controller/Solr/SolrController.java new file mode 100644 index 0000000..5366aae --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/controller/Solr/SolrController.java @@ -0,0 +1,51 @@ +package xy.SpringBoot2NoSQL.controller.Solr; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import xy.SpringBoot2NoSQL.model.Solr.Customer; +import xy.SpringBoot2NoSQL.repository.Solr.SolrCustomerRepository; + +@RestController +@RequestMapping("/solr") +public class SolrController { + + @Autowired + SolrCustomerRepository customerRepository; + + @RequestMapping("/add") + public String add(){ + + customerRepository.deleteAll(); + customerRepository.saveAll(Arrays.asList(new Customer("1", "Jack", 20), + new Customer("2", "Adam", 24), + new Customer("3", "Kim", 27), + new Customer("4", "David", 30), + new Customer("5", "Peter", 21))); + + return "ok"; + } + + @RequestMapping("/all") + public Iterable getAll(){ + + return customerRepository.findAll(); + } + + @RequestMapping("/getByID/{id}") + public Optional getByID(@PathVariable("id") String id){ + + return customerRepository.findById(id); + } + + @RequestMapping("/findByNameEndsWith/{name}") + public List findByNameEndsWith(@PathVariable("name") String name){ + + return customerRepository.findByNameEndsWith(name); + } +} diff --git a/src/main/java/xy/SpringBoot2NoSQL/exception/CreateIndexFailedException.java b/src/main/java/xy/SpringBoot2NoSQL/exception/CreateIndexFailedException.java new file mode 100644 index 0000000..8bc5539 --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/exception/CreateIndexFailedException.java @@ -0,0 +1,7 @@ +package xy.SpringBoot2NoSQL.exception; + +public class CreateIndexFailedException extends RuntimeException { + public CreateIndexFailedException(String indexName, Throwable cause) { + super(String.format("Creating Index '%s' failed", indexName), cause); + } +} diff --git a/src/main/java/xy/SpringBoot2NoSQL/exception/GetMappingFailedException.java b/src/main/java/xy/SpringBoot2NoSQL/exception/GetMappingFailedException.java new file mode 100644 index 0000000..1bcfa8d --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/exception/GetMappingFailedException.java @@ -0,0 +1,7 @@ +package xy.SpringBoot2NoSQL.exception; + +public class GetMappingFailedException extends RuntimeException { + public GetMappingFailedException(String indexName, Throwable cause) { + super(String.format("Create Mapping failed for Index '%s'", indexName), cause); + } +} diff --git a/src/main/java/xy/SpringBoot2NoSQL/exception/IndicesExistsFailedException.java b/src/main/java/xy/SpringBoot2NoSQL/exception/IndicesExistsFailedException.java new file mode 100644 index 0000000..f31c8dd --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/exception/IndicesExistsFailedException.java @@ -0,0 +1,7 @@ +package xy.SpringBoot2NoSQL.exception; + +public class IndicesExistsFailedException extends RuntimeException { + public IndicesExistsFailedException(String indexName, Throwable cause) { + super(String.format("Indices '%s' failed", indexName), cause); + } +} \ No newline at end of file diff --git a/src/main/java/xy/SpringBoot2NoSQL/exception/PutMappingFailedException.java b/src/main/java/xy/SpringBoot2NoSQL/exception/PutMappingFailedException.java new file mode 100644 index 0000000..85c3b65 --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/exception/PutMappingFailedException.java @@ -0,0 +1,7 @@ +package xy.SpringBoot2NoSQL.exception; + +public class PutMappingFailedException extends RuntimeException { + public PutMappingFailedException(String indexName, Throwable cause) { + super(String.format("Put Mapping failed for Index '%s'", indexName), cause); + } +} diff --git a/src/main/java/xy/SpringBoot2NoSQL/model/Cassandra/Customer.java b/src/main/java/xy/SpringBoot2NoSQL/model/Cassandra/Customer.java new file mode 100644 index 0000000..1c78fd8 --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/model/Cassandra/Customer.java @@ -0,0 +1,76 @@ +package xy.SpringBoot2NoSQL.model.Cassandra; + +import java.util.HashSet; +import java.util.Set; + +import org.springframework.data.cassandra.core.mapping.Column; +import org.springframework.data.cassandra.core.mapping.PrimaryKey; +import org.springframework.data.cassandra.core.mapping.Table; + +@Table +public class Customer { + + @PrimaryKey + private String id; + private String firstname; + private String lastname; + private int age; + +// @Column +// private Set tags = new HashSet<>(); + + public Customer(){} + + public Customer(String id, String firstname, String lastname, int age){ + this.id = id; + this.firstname = firstname; + this.lastname = lastname; + this.age = age; + } + + public void setId(String id){ + this.id = id; + } + + public String getId(){ + return this.id; + } + + public void setFirstname(String firstname){ + this.firstname = firstname; + } + + public String getFirstname(){ + return this.firstname; + } + + public void setLastname(String lastname){ + this.lastname = lastname; + } + + public String getLastname(){ + return this.lastname; + } + + public void setAge(int age){ + this.age = age; + } + + public int getAge(){ + return this.age; + } + +// public Set getTags() { +// return tags; +// } +// +// public void setTags(final Set tags) { +// this.tags = tags; +// } + + @Override + public String toString() { + return String.format("Customer[id=%d, firstName='%s', lastName='%s', age=%d]", this.id, + this.firstname, this.lastname, this.age); + } +} diff --git a/src/main/java/xy/SpringBoot2NoSQL/model/Couchbase/Customer.java b/src/main/java/xy/SpringBoot2NoSQL/model/Couchbase/Customer.java new file mode 100644 index 0000000..71bff3e --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/model/Couchbase/Customer.java @@ -0,0 +1,55 @@ +//package xy.SpringBoot2NoSQL.model.Couchbase; +// +//import org.springframework.data.couchbase.core.mapping.Document; +// +//import com.couchbase.client.java.repository.annotation.Field; +//import com.couchbase.client.java.repository.annotation.Id; +// +// +//@Document +//public class Customer { +// @Id +// private String id; +// +// @Field +// private String firstName; +// +// @Field +// private String lastName; +// +// public Customer(String id, String firstName, String lastName){ +// this.id = id; +// this.firstName = firstName; +// this.lastName = lastName; +// } +// +// public String getId() { +// return this.id; +// } +// +// public void setId(String id) { +// this.id = id; +// } +// +// public String getFirstName() { +// return this.firstName; +// } +// +// public void setFirstName(String firstName) { +// this.firstName = firstName; +// } +// +// public String getLastName() { +// return this.lastName; +// } +// +// public void setLastName(String lastName) { +// this.lastName = lastName; +// } +// +// @Override +// public String toString() { +// return String.format("Customer[ id=%s, firstName=%s, lastName=%s]", this.id, this.firstName, this.lastName); +// } +//} +// diff --git a/src/main/java/xy/SpringBoot2NoSQL/model/ElasticSearch/Product.java b/src/main/java/xy/SpringBoot2NoSQL/model/ElasticSearch/Product.java new file mode 100644 index 0000000..b4b60a0 --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/model/ElasticSearch/Product.java @@ -0,0 +1,57 @@ +package xy.SpringBoot2NoSQL.model.ElasticSearch; + +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.Document; + +@Document(indexName = "book",type = "book" , shards = 1, replicas = 0, refreshInterval = "-1") +public class Product { + @Id + private String id; + private String name; + private String description; + private boolean enabled; + + public Product() { + } + + public Product(String id, String name, String description, boolean enabled) { + this(); + this.id = id; + this.name = name; + this.description = description; + this.enabled = enabled; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + +} diff --git a/src/main/java/xy/SpringBoot2NoSQL/model/Mongo/Department.java b/src/main/java/xy/SpringBoot2NoSQL/model/Mongo/Department.java new file mode 100644 index 0000000..629f9df --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/model/Mongo/Department.java @@ -0,0 +1,35 @@ +package xy.SpringBoot2NoSQL.model.Mongo; + +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class Department { + + @Id + private String id; + + + private String name; + + public Department(String id, String name) { + super(); + this.id = id; + this.name = name; + } + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + +} diff --git a/src/main/java/xy/SpringBoot2NoSQL/model/Mongo/Location.java b/src/main/java/xy/SpringBoot2NoSQL/model/Mongo/Location.java new file mode 100644 index 0000000..b3788de --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/model/Mongo/Location.java @@ -0,0 +1,38 @@ +package xy.SpringBoot2NoSQL.model.Mongo; + +public class Location { + + private String place; + + private String year; + + + + public Location(String place, String year) { + super(); + this.place = place; + this.year = year; + } + + public String getPlace() { + return place; + } + + public void setPlace(String place) { + this.place = place; + } + + public String getYear() { + return year; + } + + public void setYear(String year) { + this.year = year; + } + + + + + + +} \ No newline at end of file diff --git a/src/main/java/xy/SpringBoot2NoSQL/model/Mongo/Person.java b/src/main/java/xy/SpringBoot2NoSQL/model/Mongo/Person.java new file mode 100644 index 0000000..f1d0b79 --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/model/Mongo/Person.java @@ -0,0 +1,69 @@ +package xy.SpringBoot2NoSQL.model.Mongo; + +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; +import org.springframework.data.mongodb.core.mapping.Field; +import org.springframework.data.mongodb.core.mapping.DBRef; + +import java.util.Collection; +import java.util.LinkedHashSet; + +@Document +public class Person { + @Id + private String id; + private String name; + private Integer age; + @Field("locs") + private Collection locations = new LinkedHashSet(); + @DBRef + Department department; + + + public Person(String name, Integer age) { + super(); + this.name = name; + this.age = age; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + public Collection getLocations() { + return locations; + } + + public void setLocations(Collection locations) { + this.locations = locations; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + +} \ No newline at end of file diff --git a/src/main/java/xy/SpringBoot2NoSQL/model/Redis/User.java b/src/main/java/xy/SpringBoot2NoSQL/model/Redis/User.java new file mode 100644 index 0000000..2647b91 --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/model/Redis/User.java @@ -0,0 +1,49 @@ +package xy.SpringBoot2NoSQL.model.Redis; + +import java.io.Serializable; +import java.util.Date; + +public class User implements Serializable{ + + private static final long serialVersionUID = 1945136152785232109L; + + private String login; + + private String fullName; + + private Date lastLogin; + + public User() {} + + public User(String login, String fullName) { + this.login = login; + this.fullName = fullName; + this.lastLogin = new Date(); + } + + public String getLogin() { + return login; + } + + public void setLogin(String login) { + this.login = login; + } + + public String getFullName() { + return fullName; + } + + public void setFullName(String fullName) { + this.fullName = fullName; + } + + public Date getLastLogin() { + return lastLogin; + } + + public void setLastLogin(Date lastLogin) { + this.lastLogin = lastLogin; + } + +} + diff --git a/src/main/java/xy/SpringBoot2NoSQL/model/Solr/Customer.java b/src/main/java/xy/SpringBoot2NoSQL/model/Solr/Customer.java new file mode 100644 index 0000000..04ac131 --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/model/Solr/Customer.java @@ -0,0 +1,57 @@ +package xy.SpringBoot2NoSQL.model.Solr; + +import org.apache.solr.client.solrj.beans.Field; +import org.springframework.data.annotation.Id; +import org.springframework.data.solr.core.mapping.SolrDocument; + +@SolrDocument(collection = "customer") +public class Customer { + @Id + @Field + private String id; + + @Field + private String name; + + @Field + private Integer age; + + public Customer() { + } + + public Customer(String id, String name, Integer age){ + this.id = id; + this.name = name; + this.age = age; + } + + public void setId(String id){ + this.id = id; + } + + public String getId(){ + return this.id; + } + + public void setName(String name){ + this.name = name; + } + + public String getName(){ + return this.name; + } + + public void setAge(Integer age){ + this.age = age; + } + + public Integer getAge(){ + return this.age; + } + + @Override + public String toString() { + return "Customer [id=" + this.id + ", name=" + this.name + ", age=" + this.age + "]"; + } +} + diff --git a/src/main/java/xy/SpringBoot2NoSQL/model/User.java b/src/main/java/xy/SpringBoot2NoSQL/model/User.java new file mode 100644 index 0000000..e81ae3b --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/model/User.java @@ -0,0 +1,54 @@ +package xy.SpringBoot2NoSQL.model; + +import java.io.Serializable; +import java.util.Date; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +public class User implements Serializable{ + + private static final long serialVersionUID = -510562806568452731L; + + Logger logger = LogManager.getLogger(getClass()); + + private String login; + + private String fullName; + + private Date lastLogin; + + public User() {} + + public User(String login, String fullName) { + this.login = login; + this.fullName = fullName; + this.lastLogin = new Date(); + } + + public String getLogin() { + return login; + } + + public void setLogin(String login) { + this.login = login; + } + + public String getFullName() { + return fullName; + } + + public void setFullName(String fullName) { + this.fullName = fullName; + } + + public Date getLastLogin() { + return lastLogin; + } + + public void setLastLogin(Date lastLogin) { + this.lastLogin = lastLogin; + } + +} + diff --git a/src/main/java/xy/SpringBoot2NoSQL/repository/Cassandra/CustomerRepository.java b/src/main/java/xy/SpringBoot2NoSQL/repository/Cassandra/CustomerRepository.java new file mode 100644 index 0000000..258d394 --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/repository/Cassandra/CustomerRepository.java @@ -0,0 +1,25 @@ +package xy.SpringBoot2NoSQL.repository.Cassandra; + +import java.util.List; + +import org.springframework.data.cassandra.repository.AllowFiltering; +import org.springframework.data.cassandra.repository.CassandraRepository; +import org.springframework.data.cassandra.repository.Query; + + +import xy.SpringBoot2NoSQL.model.Cassandra.Customer; + +public interface CustomerRepository extends CassandraRepository { + + @Query(value="SELECT * FROM customer WHERE firstname=?0") + public List findByFirstname(String firstname); + + @Query("SELECT * FROM customer WHERE age > ?0") + public List findCustomerHasAgeGreaterThan(int age); + + @AllowFiltering + public List findByLastname(String lastname); + + @AllowFiltering + public List findByAgeGreaterThan(int age); +} \ No newline at end of file diff --git a/src/main/java/xy/SpringBoot2NoSQL/repository/Couchbase/CouchbaseCustomerRepository.java b/src/main/java/xy/SpringBoot2NoSQL/repository/Couchbase/CouchbaseCustomerRepository.java new file mode 100644 index 0000000..de1f756 --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/repository/Couchbase/CouchbaseCustomerRepository.java @@ -0,0 +1,17 @@ +//package xy.SpringBoot2NoSQL.repository.Couchbase; +// +//import java.util.List; +// +//import org.springframework.data.couchbase.core.query.N1qlPrimaryIndexed; +//import org.springframework.data.couchbase.core.query.ViewIndexed; +//import org.springframework.data.couchbase.repository.CouchbaseRepository; +// +//import xy.SpringBoot2NoSQL.model.Couchbase.Customer; +// +// +//@N1qlPrimaryIndexed +//@ViewIndexed(designDoc = "customer", viewName = "all") +//public interface CouchbaseCustomerRepository extends CouchbaseRepository { +// +// List findByLastName(String name); +//} diff --git a/src/main/java/xy/SpringBoot2NoSQL/repository/ElasticSearch/SampleProductRepository.java b/src/main/java/xy/SpringBoot2NoSQL/repository/ElasticSearch/SampleProductRepository.java new file mode 100644 index 0000000..681bcc7 --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/repository/ElasticSearch/SampleProductRepository.java @@ -0,0 +1,15 @@ +package xy.SpringBoot2NoSQL.repository.ElasticSearch; + +import org.springframework.data.domain.Pageable; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; + +import xy.SpringBoot2NoSQL.model.ElasticSearch.Product; + +import java.util.List; + +public interface SampleProductRepository extends ElasticsearchRepository { + List findByName(String name); + List findByDescription(String description); + List findByName(String name, Pageable pageable); + List findByNameAndId(String name, String id); +} diff --git a/src/main/java/xy/SpringBoot2NoSQL/repository/Mongo/DepartmentRepository.java b/src/main/java/xy/SpringBoot2NoSQL/repository/Mongo/DepartmentRepository.java new file mode 100644 index 0000000..563d2a1 --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/repository/Mongo/DepartmentRepository.java @@ -0,0 +1,13 @@ +package xy.SpringBoot2NoSQL.repository.Mongo; + +import org.springframework.data.mongodb.repository.MongoRepository; + +import xy.SpringBoot2NoSQL.model.Mongo.Department; + + +public interface DepartmentRepository extends MongoRepository { + + Department findByName(String name); + +} + diff --git a/src/main/java/xy/SpringBoot2NoSQL/repository/Mongo/PersonRepository.java b/src/main/java/xy/SpringBoot2NoSQL/repository/Mongo/PersonRepository.java new file mode 100644 index 0000000..6ff6944 --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/repository/Mongo/PersonRepository.java @@ -0,0 +1,20 @@ +package xy.SpringBoot2NoSQL.repository.Mongo; + + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.data.mongodb.repository.Query; +import xy.SpringBoot2NoSQL.model.Mongo.Person; +import java.util.List; + +public interface PersonRepository extends MongoRepository { + + Person findByName(String name); + + @Query("{'age': { '$lt' : ?0}}") + List withQueryFindByAge(Integer age); + + Page findAll(Pageable pageable); + +} diff --git a/src/main/java/xy/SpringBoot2NoSQL/repository/Redis/ObjectRepository.java b/src/main/java/xy/SpringBoot2NoSQL/repository/Redis/ObjectRepository.java new file mode 100644 index 0000000..34a5be0 --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/repository/Redis/ObjectRepository.java @@ -0,0 +1,27 @@ +package xy.SpringBoot2NoSQL.repository.Redis; + +import javax.annotation.Resource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.ValueOperations; +import org.springframework.stereotype.Repository; + +import xy.SpringBoot2NoSQL.model.Redis.User; + +@Repository +public class ObjectRepository { + @Autowired + RedisTemplate redisTemplate; + + @Resource(name = "redisTemplate") + ValueOperations valOps; + + public void save(User user) { + valOps.set(user.getLogin(), user); + } + + public User get(String id) { + return (User) valOps.get(id); + } +} diff --git a/src/main/java/xy/SpringBoot2NoSQL/repository/Redis/StringStringRepository.java b/src/main/java/xy/SpringBoot2NoSQL/repository/Redis/StringStringRepository.java new file mode 100644 index 0000000..a454afe --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/repository/Redis/StringStringRepository.java @@ -0,0 +1,25 @@ +package xy.SpringBoot2NoSQL.repository.Redis; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Repository; + +@Repository +public class StringStringRepository { + + @Autowired + private RedisTemplate template; + + public void add(String key, String value) { + template.opsForValue().set(key, value); + } + + public String getValue(String key) { + return template.opsForValue().get(key); + } + + public void delete(String key) { + template.opsForValue().getOperations().delete(key); + } + +} \ No newline at end of file diff --git a/src/main/java/xy/SpringBoot2NoSQL/repository/Redis/UserRepository.java b/src/main/java/xy/SpringBoot2NoSQL/repository/Redis/UserRepository.java new file mode 100644 index 0000000..ccd6fab --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/repository/Redis/UserRepository.java @@ -0,0 +1,30 @@ +package xy.SpringBoot2NoSQL.repository.Redis; + +import javax.annotation.Resource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.ValueOperations; +import org.springframework.stereotype.Repository; + +import xy.SpringBoot2NoSQL.model.Redis.User; + +@Repository +public class UserRepository { + +// @Autowired +// RedisTemplate redisTemplate; +// +// @Resource(name = "redisTemplate") +// ValueOperations valOps; +// +// public void save(User user) { +// valOps.set(user.getLogin(), user); +// } +// +// public User get(String id) { +// return valOps.get(id); +// } + + +} \ No newline at end of file diff --git a/src/main/java/xy/SpringBoot2NoSQL/repository/Solr/SolrCustomerRepository.java b/src/main/java/xy/SpringBoot2NoSQL/repository/Solr/SolrCustomerRepository.java new file mode 100644 index 0000000..4b78648 --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/repository/Solr/SolrCustomerRepository.java @@ -0,0 +1,10 @@ +package xy.SpringBoot2NoSQL.repository.Solr; + +import java.util.List; +import org.springframework.data.solr.repository.SolrCrudRepository; +import xy.SpringBoot2NoSQL.model.Solr.Customer; + + +public interface SolrCustomerRepository extends SolrCrudRepository { + List findByNameEndsWith(String name); +} diff --git a/src/main/java/xy/SpringBoot2NoSQL/service/Ehcache/UserService.java b/src/main/java/xy/SpringBoot2NoSQL/service/Ehcache/UserService.java new file mode 100644 index 0000000..3ca2c39 --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/service/Ehcache/UserService.java @@ -0,0 +1,49 @@ +package xy.SpringBoot2NoSQL.service.Ehcache; + +import org.springframework.cache.annotation.CacheConfig; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.stereotype.Service; +import net.sf.ehcache.Cache; +import net.sf.ehcache.CacheManager; +import net.sf.ehcache.Element; +import xy.SpringBoot2NoSQL.model.User; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +@Service +@CacheConfig(cacheNames="users") +public class UserService { + + Logger logger = LogManager.getLogger(getClass()); + + @CacheEvict(allEntries = true) + public void clearCache(){} + + public User getUser(String login) { + // 获取缓存实例 + Cache userCache = CacheManager.getInstance().getCache("users"); + + if (userCache.get(login)!=null){ + + User user = (User) userCache.get(login).getObjectValue(); + logger.info("从缓存获取user用户: {}", login); + logger.info("从缓存JVM内存中获取获取user用户: {}-{}",login, userCache.isElementInMemory(login)); + logger.info("从缓存OffHeap内存中获取获取user用户: {}-{}",login, userCache.isElementOffHeap(login)); + logger.info("已持久化磁盘,用户: {}-{}",login, userCache.isElementOnDisk(login)); + + return user; + } + else{ + User user = new User(login,login+"的姓名"); + logger.info("新user用户: {}", login); + // 写入缓存,注意我们故意设置maxElementsInMemory内存最大值是5 + Element element = new Element(login, user); + userCache.put(element); + + return user; + } + + } + +} diff --git a/src/main/java/xy/SpringBoot2NoSQL/utils/ESSearchUtil.java b/src/main/java/xy/SpringBoot2NoSQL/utils/ESSearchUtil.java new file mode 100644 index 0000000..0e70f5b --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/utils/ESSearchUtil.java @@ -0,0 +1,160 @@ +package xy.SpringBoot2NoSQL.utils; + +import java.io.IOException; + +import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder; +import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; +import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse; +import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest; +import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse; +import org.elasticsearch.client.Client; +import org.elasticsearch.index.query.QueryBuilder; +import org.elasticsearch.index.query.QueryBuilders; + +import xy.SpringBoot2NoSQL.exception.CreateIndexFailedException; +import xy.SpringBoot2NoSQL.exception.IndicesExistsFailedException; +import xy.SpringBoot2NoSQL.exception.PutMappingFailedException; + +public class ESSearchUtil { + + /** + * 索引是否存在 + * @param client + * @param indexName + * @return + */ + public static IndicesExistsResponse indexExist(Client client, String indexName) { + try { + return client.admin().indices().prepareExists(indexName).execute().actionGet(); + } catch (Exception e) { + + throw new IndicesExistsFailedException(indexName, e); + } + } + + /** + * 创建索引 + * @param client + * @param indexName + * @return + */ + public static CreateIndexResponse createIndex(Client client, String indexName) { + try { + return internalCreateIndex(client, indexName); + } catch (Exception e) { + throw new CreateIndexFailedException(indexName, e); + } + } + + public static PutMappingResponse putMapping(Client client, String indexName, IElasticSearchMapping mapping) { + try { + return internalPutMapping(client, indexName, mapping); + } catch (Exception e) { + + throw new PutMappingFailedException(indexName, e); + } + } + + private static CreateIndexResponse internalCreateIndex(Client client, String indexName) throws IOException { + final CreateIndexRequestBuilder createIndexRequestBuilder = client.admin().indices().prepareCreate(indexName); + + final CreateIndexResponse indexResponse = createIndexRequestBuilder.execute().actionGet(); + + return indexResponse; + } + + private static PutMappingResponse internalPutMapping(Client client, String indexName, IElasticSearchMapping mapping) + throws IOException { + + final PutMappingRequest putMappingRequest = new PutMappingRequest(indexName).type(mapping.getIndexType()) + .source(mapping.getMapping().string()); + + final PutMappingResponse putMappingResponse = client.admin().indices().putMapping(putMappingRequest) + .actionGet(); + + return putMappingResponse; + } + + /** + * 部分匹配查询,包括模糊匹配和短语或邻近查询。 + * + * @param key + * @param value + * @return + */ + public static QueryBuilder matchQuery(String key, String value) { + return QueryBuilders.matchQuery(key, value); + } + + /** + * 完全匹配。 + * + * @param key + * @param value + * @return + */ + public static QueryBuilder matchPhraseQuery(String key, String value) { + return QueryBuilders.matchPhraseQuery(key, value); + } + + /** + * 多字段匹配 + * + * @param text + * @param fieldNames + * @return + */ + public static QueryBuilder multiMatchQuery(Object text, String... fieldNames) { + return QueryBuilders.multiMatchQuery(text, fieldNames); + + } + + /** + * 模糊查询 + * + * @param key + * @param value + * @return + */ + public static QueryBuilder fuzzyQuery(String key, String value) { + return QueryBuilders.fuzzyQuery(key, value); + } + + /** + * 全部查询 + * + * @return + */ + public static QueryBuilder matchAllQuery() { + return QueryBuilders.matchAllQuery(); + } + + /** + * 范围查询 + * + * @param key + * @param from + * @param to + * @return + */ + public static QueryBuilder rangeQuery(String key, Object from, Object to) { + return QueryBuilders.rangeQuery(key).from(from).to(to).includeLower(true) // 包括下界 + .includeUpper(false); // 包括上界 + } + + /** + * 完全匹配查询 + * + * @param key + * @param values + * @return + */ + public static QueryBuilder termsQuery(String key, String... values) { + return QueryBuilders.termsQuery(key, values); + } + + public static QueryBuilder termsQuery(String key, Object values) { + return QueryBuilders.termsQuery(key, values); + } + +} diff --git a/src/main/java/xy/SpringBoot2NoSQL/utils/IElasticSearchMapping.java b/src/main/java/xy/SpringBoot2NoSQL/utils/IElasticSearchMapping.java new file mode 100644 index 0000000..eb6b04e --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/utils/IElasticSearchMapping.java @@ -0,0 +1,14 @@ +package xy.SpringBoot2NoSQL.utils; + +import org.elasticsearch.Version; +import org.elasticsearch.common.xcontent.XContentBuilder; + +public interface IElasticSearchMapping { + + XContentBuilder getMapping(); + + String getIndexType(); + + Version getVersion(); + +} \ No newline at end of file diff --git a/src/main/java/xy/SpringBoot2NoSQL/utils/RandomUtil.java b/src/main/java/xy/SpringBoot2NoSQL/utils/RandomUtil.java new file mode 100644 index 0000000..b88cafb --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/utils/RandomUtil.java @@ -0,0 +1,120 @@ +package xy.SpringBoot2NoSQL.utils; + +import java.util.Random; + +public class RandomUtil { + public static final String ALLCHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + public static final String LETTERCHAR = "abcdefghijkllmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + public static final String NUMBERCHAR = "0123456789"; + + /** + * 返回一个定长的随机字符串(只包含大小写字母、数字) + * + * @param length + * 随机字符串长度 + * @return 随机字符串 + */ + public static String generateString(int length) { + StringBuffer sb = new StringBuffer(); + Random random = new Random(); + for (int i = 0; i < length; i++) { + sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length()))); + } + return sb.toString(); + } + + /** + * 返回一个定长的随机纯字母字符串(只包含大小写字母) + * + * @param length + * 随机字符串长度 + * @return 随机字符串 + */ + public static String generateMixString(int length) { + StringBuffer sb = new StringBuffer(); + Random random = new Random(); + for (int i = 0; i < length; i++) { + sb.append(ALLCHAR.charAt(random.nextInt(LETTERCHAR.length()))); + } + return sb.toString(); + } + + /** + * 返回一个定长的随机纯大写字母字符串(只包含大小写字母) + * + * @param length + * 随机字符串长度 + * @return 随机字符串 + */ + public static String generateLowerString(int length) { + return generateMixString(length).toLowerCase(); + } + + /** + * 返回一个定长的随机纯小写字母字符串(只包含大小写字母) + * + * @param length + * 随机字符串长度 + * @return 随机字符串 + */ + public static String generateUpperString(int length) { + return generateMixString(length).toUpperCase(); + } + + /** + * 生成一个定长的纯0字符串 + * + * @param length + * 字符串长度 + * @return 纯0字符串 + */ + public static String generateZeroString(int length) { + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < length; i++) { + sb.append('0'); + } + return sb.toString(); + } + + /** + * 根据数字生成一个定长的字符串,长度不够前面补0 + * + * @param num + * 数字 + * @param fixdlenth + * 字符串长度 + * @return 定长的字符串 + */ + public static String toFixdLengthString(long num, int fixdlenth) { + StringBuffer sb = new StringBuffer(); + String strNum = String.valueOf(num); + if (fixdlenth - strNum.length() >= 0) { + sb.append(generateZeroString(fixdlenth - strNum.length())); + } else { + throw new RuntimeException("将数字" + num + "转化为长度为" + fixdlenth + "的字符串发生异常!"); + } + sb.append(strNum); + return sb.toString(); + } + + /** + * 每次生成的len位数都不相同 + * + * @param param + * @return 定长的数字 + */ + public static int getNotSimple(int[] param, int len) { + Random rand = new Random(); + for (int i = param.length; i > 1; i--) { + int index = rand.nextInt(i); + int tmp = param[index]; + param[index] = param[i - 1]; + param[i - 1] = tmp; + } + int result = 0; + for (int i = 0; i < len; i++) { + result = result * 10 + param[i]; + } + return result; + } +} \ No newline at end of file diff --git a/src/main/java/xy/SpringBoot2NoSQL/utils/RedisCacheUtils.java b/src/main/java/xy/SpringBoot2NoSQL/utils/RedisCacheUtils.java new file mode 100644 index 0000000..b8e3898 --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/utils/RedisCacheUtils.java @@ -0,0 +1,649 @@ +//package xy.SpringBoot2NoSQL.utils; +// +//import java.util.ArrayList; +//import java.util.List; +//import java.util.Map; +//import java.util.Set; +//import java.util.concurrent.TimeUnit; +// +//import javax.annotation.PostConstruct; +//import javax.annotation.Resource; +// +//import org.springframework.data.redis.connection.RedisZSetCommands; +//import org.springframework.data.redis.core.ListOperations; +//import org.springframework.data.redis.core.RedisCallback; +//import org.springframework.data.redis.core.RedisTemplate; +//import org.springframework.data.redis.core.SetOperations; +//import org.springframework.data.redis.core.ValueOperations; +// +//import com.alibaba.fastjson.JSON; +//import com.alibaba.fastjson.parser.Feature; +// +//public class RedisCacheUtils { +// @Resource +// private RedisTemplate redisTemplate; +// +// private static RedisCacheUtils cacheUtils; +// +// @PostConstruct +// public void init() { +// cacheUtils = this; +// cacheUtils.redisTemplate = this.redisTemplate; +// } +// +// /** +// * 将数据存入缓存 +// * +// * @param key +// * @param val +// * @return +// */ +// public static void saveString(String key, String val) { +// +// ValueOperations vo = cacheUtils.redisTemplate.opsForValue(); +// vo.set(key, val); +// } +// +// /** +// * 将数据存入缓存的集合中 +// * +// * @param key +// * @param val +// * @return +// */ +// public static void saveToSet(String key, String val) { +// +// SetOperations so = cacheUtils.redisTemplate.opsForSet(); +// +// so.add(key, val); +// } +// +// /** +// * key 缓存Key +// * @param key +// * @return +// */ +// public static String getFromSet(String key) { +// return cacheUtils.redisTemplate.opsForSet().pop(key); +// } +// +// /** +// * 将 key的值保存为 value ,当且仅当 key 不存在。 若给定的 key 已经存在,则 SETNX 不做任何动作。 SETNX 是『SET if +// * Not eXists』(如果不存在,则 SET)的简写。
+// * 保存成功,返回 true
+// * 保存失败,返回 false +// */ +// public static boolean saveNX(String key, String val) { +// +// /** 设置成功,返回 1 设置失败,返回 0 **/ +// return cacheUtils.redisTemplate.execute((RedisCallback) connection -> { +// return connection.setNX(key.getBytes(), val.getBytes()); +// }); +// +// } +// +// /** +// * 将 key的值保存为 value ,当且仅当 key 不存在。 若给定的 key 已经存在,则 SETNX 不做任何动作。 SETNX 是『SET if +// * Not eXists』(如果不存在,则 SET)的简写。
+// * 保存成功,返回 true
+// * 保存失败,返回 false +// * +// * @param key +// * @param val +// * @param expire 超时时间 +// * @return 保存成功,返回 true 否则返回 false +// */ +// public static boolean saveNX(String key, String val, int expire) { +// +// boolean ret = saveNX(key, val); +// if (ret) { +// cacheUtils.redisTemplate.expire(key, expire, TimeUnit.SECONDS); +// } +// return ret; +// } +// +// /** +// * 将数据存入缓存(并设置失效时间) +// * +// * @param key +// * @param val +// * @param seconds +// * @return +// */ +// public static void saveString(String key, String val, int seconds) { +// +// cacheUtils.redisTemplate.opsForValue().set(key, val, seconds, TimeUnit.SECONDS); +// } +// +// /** +// * 将自增变量存入缓存 +// */ +// public static void saveSeq(String key, long seqNo) { +// +// cacheUtils.redisTemplate.delete(key); +// cacheUtils.redisTemplate.opsForValue().increment(key, seqNo); +// } +// +// /** +// * 将递增浮点数存入缓存 +// */ +// public static void saveFloat(String key, float data) { +// +// cacheUtils.redisTemplate.delete(key); +// cacheUtils.redisTemplate.opsForValue().increment(key, data); +// } +// +// /** +// * 保存复杂类型数据到缓存 +// * +// * @param key +// * @param obj +// * @return +// */ +// public static void saveBean(String key, Object obj) { +// +// cacheUtils.redisTemplate.opsForValue().set(key, JSON.toJSONString(obj)); +// } +// +// /** +// * 保存复杂类型数据到缓存(并设置失效时间) +// * +// * @param key +// * @param obj +// * @param seconds +// */ +// public static void saveBean(String key, Object obj, int seconds) { +// +// cacheUtils.redisTemplate.opsForValue().set(key, JSON.toJSONString(obj), seconds, TimeUnit.SECONDS); +// } +// +// /** +// * 存到指定的队列中 +// * @param key +// * @param val +// * @param size +// */ +// public static void saveToQueue(String key, String val, long size) { +// +// ListOperations lo = cacheUtils.redisTemplate.opsForList(); +// +// if (size > 0 && lo.size(key) >= size) { +// lo.rightPop(key); +// } +// lo.leftPush(key, val); +// } +// +// /** +// * 保存到hash集合中 +// * +// * @param hName 集合名 +// * @param key +// * @param value +// */ +// public static void hashSet(String hName, String key, String value) { +// +// cacheUtils.redisTemplate.opsForHash().put(hName, key, value); +// } +// +// /** +// * 根据key获取所以值 +// * +// * @param key +// * @return +// */ +// public static Map hgetAll(String key) { +// +// return cacheUtils.redisTemplate.opsForHash().entries(key); +// } +// +// /** +// * 保存到hash集合中 +// * +// * @param +// * @param hName 集合名 +// * @param key +// * @param t +// */ +// public static void hashSet(String hName, String key, T t) { +// +// hashSet(hName, key, JSON.toJSONString(t)); +// } +// +// /** +// * 取得复杂JSON数据 +// * +// * @param key +// * @param clazz +// * @param clazz +// * @return +// */ +// public static T getBean(String key, Class clazz) { +// +// String value = cacheUtils.redisTemplate.opsForValue().get(key); +// if (value == null) { +// return null; +// } +// return JSON.parseObject(value, clazz); +// } +// +// /** +// * 从缓存中取得字符串数据 +// * +// * @param key +// * @return 数据 +// */ +// public static String getString(String key) { +// cacheUtils.redisTemplate.opsForValue().get(key); +// +// return cacheUtils.redisTemplate.opsForValue().get(key); +// } +// +// /** +// * 从指定队列里取得数据 +// * @param key +// * @param size +// * @return +// */ +// public static List getFromQueue(String key, long size) { +// +// boolean flag = cacheUtils.redisTemplate.execute((RedisCallback) connection -> { +// return connection.exists(key.getBytes()); +// }); +// +// if (flag) { +// return new ArrayList<>(); +// } +// ListOperations lo = cacheUtils.redisTemplate.opsForList(); +// if (size > 0) { +// return lo.range(key, 0, size - 1); +// } else { +// return lo.range(key, 0, lo.size(key) - 1); +// } +// } +// +// /** +// * 从指定队列里取得数据 +// * @param key +// * @return +// */ +// public static String popQueue(String key) { +// +// return cacheUtils.redisTemplate.opsForList().rightPop(key); +// +// } +// +// /** +// * 取得序列值的下一个 +// * +// * @param key +// * @return +// */ +// public static Long getSeqNext(String key) { +// +// return cacheUtils.redisTemplate.execute((RedisCallback) connection -> { +// +// return connection.incr(key.getBytes()); +// +// }); +// } +// +// /** +// * 取得序列值的下一个 +// * +// * @param key +// * @return +// */ +// public static Long getSeqNext(String key, long value) { +// +// return cacheUtils.redisTemplate.execute((RedisCallback) connection -> { +// +// return connection.incrBy(key.getBytes(), value); +// +// }); +// +// } +// +// /** +// * 将序列值回退一个 +// * +// * @param key +// * @return +// */ +// public static void getSeqBack(String key) { +// +// cacheUtils.redisTemplate.execute((RedisCallback) connection -> connection.decr(key.getBytes())); +// +// } +// +// /** +// * 从hash集合里取得 +// * +// * @param hName +// * @param key +// * @return +// */ +// public static Object hashGet(String hName, String key) { +// +// return cacheUtils.redisTemplate.opsForHash().get(hName, key); +// } +// +// public static T hashGet(String hName, String key, Class clazz) { +// +// return JSON.parseObject((String) hashGet(hName, key), clazz); +// } +// +// /** +// * 增加浮点数的值 +// * +// * @param key +// * @return +// */ +// public static Double incrFloat(String key, double incrBy) { +// +// return cacheUtils.redisTemplate.execute((RedisCallback) connection -> { +// +// return connection.incrBy(key.getBytes(), incrBy); +// +// }); +// } +// +// /** +// * 判断是否缓存了数据 +// * +// * @param key 数据KEY +// * @return 判断是否缓存了 +// */ +// public static boolean isCached(String key) { +// +// return cacheUtils.redisTemplate.execute((RedisCallback) connection -> { +// return connection.exists(key.getBytes()); +// }); +// } +// +// /** +// * 判断hash集合中是否缓存了数据 +// * +// * @param hName +// * @param key 数据KEY +// * @return 判断是否缓存了 +// */ +// public static boolean hashCached(String hName, String key) { +// +// return cacheUtils.redisTemplate.execute((RedisCallback) connection -> { +// return connection.hExists(key.getBytes(), key.getBytes()); +// }); +// } +// +// /** +// * 判断是否缓存在指定的集合中 +// * +// * @param key 数据KEY +// * @param val 数据 +// * @return 判断是否缓存了 +// */ +// public static boolean isMember(String key, String val) { +// +// return cacheUtils.redisTemplate.execute((RedisCallback) connection -> { +// return connection.sIsMember(key.getBytes(), val.getBytes()); +// }); +// } +// +// /** +// * 从缓存中删除数据 +// * +// * @param key +// * @return +// */ +// public static void delKey(String key) { +// +// cacheUtils.redisTemplate.execute((RedisCallback) connection -> connection.del(key.getBytes())); +// } +// +// /** +// * 设置超时时间 +// * +// * @param key +// * @param seconds +// */ +// public static void expire(String key, int seconds) { +// cacheUtils.redisTemplate +// .execute((RedisCallback) connection -> connection.expire(key.getBytes(), seconds)); +// +// } +// +// /** +// * 列出set中所有成员 +// * +// * @param setName set名 +// * @return +// */ +// public static Set listSet(String setName) { +// +// return cacheUtils.redisTemplate.opsForHash().keys(setName); +// +// } +// +// /** +// * 向set中追加一个值 +// * +// * @param setName set名 +// * @param value +// */ +// public static void setSave(String setName, String value) { +// +// cacheUtils.redisTemplate +// .execute((RedisCallback) connection -> connection.sAdd(setName.getBytes(), value.getBytes())); +// +// } +// +// /** +// * 逆序列出sorted set包括分数的set列表 +// * +// * @param key set名 +// * @param start 开始位置 +// * @param end 结束位置 +// * @return 列表 +// */ +// public static Set listSortedsetRev(String key, int start, int end) { +// +// return cacheUtils.redisTemplate.execute((RedisCallback>) connection -> { +// return connection.zRevRangeWithScores(key.getBytes(), start, end); +// }); +// } +// +// /** +// * 逆序取得sorted sort排名 +// * +// * @param key set名 +// * @param member 成员名 +// * @return 排名 +// */ +// public static Long getRankRev(String key, String member) { +// +// return cacheUtils.redisTemplate.execute((RedisCallback) connection -> { +// return connection.zRevRank(key.getBytes(), member.getBytes()); +// }); +// +// } +// +// /** +// * 根据成员名取得sorted sort分数 +// * +// * @param key set名 +// * @param member 成员名 +// * @return 分数 +// */ +// public static Double getMemberScore(String key, String member) { +// +// return cacheUtils.redisTemplate.execute((RedisCallback) connection -> { +// return connection.zScore(key.getBytes(), member.getBytes()); +// }); +// } +// +// /** +// * 向sorted set中追加一个值 +// * +// * @param key set名 +// * @param score 分数 +// * @param member 成员名称 +// */ +// public static void saveToSortedset(String key, Double score, String member) { +// +// cacheUtils.redisTemplate.execute( +// (RedisCallback) connection -> connection.zAdd(key.getBytes(), score, member.getBytes())); +// } +// +// /** +// * 从sorted set删除一个值 +// * +// * @param key set名 +// * @param member 成员名称 +// */ +// public static void delFromSortedset(String key, String member) { +// cacheUtils.redisTemplate +// .execute((RedisCallback) connection -> connection.zRem(key.getBytes(), member.getBytes())); +// +// } +// +// /** +// * 从hash map中取得复杂JSON数据 +// * +// * @param key +// * @param field +// * @param clazz +// */ +// public static T getBeanFromMap(String key, String field, Class clazz) { +// +// byte[] input = cacheUtils.redisTemplate.execute((RedisCallback) connection -> { +// return connection.hGet(key.getBytes(), field.getBytes()); +// }); +// return JSON.parseObject(input, clazz, Feature.AutoCloseSource); +// } +// +// /** +// * 从hashmap中删除一个值 +// * +// * @param key map名 +// * @param field 成员名称 +// */ +// public static void delFromMap(String key, String field) { +// +// cacheUtils.redisTemplate +// .execute((RedisCallback) connection -> connection.hDel(key.getBytes(), field.getBytes())); +// +// } +// +// /** +// * @param key +// * @return +// * @Description: 根据key增长 ,计数器 +// * @author clg +// * @date 2016年6月30日 下午2:37:52 +// */ +// public static long incr(String key) { +// +// return cacheUtils.redisTemplate.execute((RedisCallback) connection -> { +// return connection.incr(key.getBytes()); +// }); +// } +// +// +// /** +// * 根据key获取当前计数结果 +// * @param key +// * @return +// */ +// public static String getCount(String key) { +// +// return cacheUtils.redisTemplate.opsForValue().get(key); +// } +// +// /** +// * 将所有指定的值插入到存于 key 的列表的头部。如果 key 不存在,那么在进行 push 操作前会创建一个空列表 +// * +// * @param +// * @param key +// * @param value +// * @return +// */ +// public static Long lpush(String key, T value) { +// +// return cacheUtils.redisTemplate.opsForList().leftPush(key, JSON.toJSONString(value)); +// } +// +// /** +// * 只有当 key 已经存在并且存着一个 list 的时候,在这个 key 下面的 list 的头部插入 value。 与 LPUSH 相反,当 key +// * 不存在的时候不会进行任何操作 +// * +// * @param key +// * @param value +// * @return +// */ +// public static Long lpushx(String key, T value) { +// +// return cacheUtils.redisTemplate.opsForList().leftPushIfPresent(key, JSON.toJSONString(value)); +// } +// +// /** +// * 返回存储在 key 里的list的长度。 如果 key 不存在,那么就被看作是空list,并且返回长度为 0 +// * +// * @param key +// * @return +// */ +// public static Long llen(String key) { +// +// return cacheUtils.redisTemplate.opsForList().size(key); +// } +// +// /** +// * 返回存储在 key 的列表里指定范围内的元素。 start 和 end +// * 偏移量都是基于0的下标,即list的第一个元素下标是0(list的表头),第二个元素下标是1,以此类推 +// * +// * @param key +// * @return +// */ +// public static List lrange(String key, long start, long end) { +// +// return cacheUtils.redisTemplate.opsForList().range(key, start, end); +// } +// +// /** +// * 移除并且返回 key 对应的 list 的第一个元素 +// * +// * @param key +// * @return +// */ +// public static String lpop(String key) { +// +// return cacheUtils.redisTemplate.opsForList().leftPop(key); +// } +// +// /** +// * 保存到hash集合中 只在 key 指定的哈希集中不存在指定的字段时,设置字段的值。如果 key 指定的哈希集不存在,会创建一个新的哈希集并与 key +// * 关联。如果字段已存在,该操作无效果。 +// * +// * @param hName 集合名 +// * @param key +// * @param value +// */ +// public static void hsetnx(String hName, String key, String value) { +// +// cacheUtils.redisTemplate.execute((RedisCallback) connection -> connection.hSetNX(key.getBytes(), +// key.getBytes(), value.getBytes())); +// +// } +// +// /** +// * 保存到hash集合中 只在 key 指定的哈希集中不存在指定的字段时,设置字段的值。如果 key 指定的哈希集不存在,会创建一个新的哈希集并与 key +// * 关联。如果字段已存在,该操作无效果。 +// * +// * @param hName 集合名 +// * @param key +// * @param t +// * @param +// */ +// public static void hsetnx(String hName, String key, T t) { +// hsetnx(hName, key, JSON.toJSONString(t)); +// } +// +//} diff --git a/src/main/java/xy/SpringBoot2NoSQL/utils/RedissonUtil.java b/src/main/java/xy/SpringBoot2NoSQL/utils/RedissonUtil.java new file mode 100644 index 0000000..3d490f7 --- /dev/null +++ b/src/main/java/xy/SpringBoot2NoSQL/utils/RedissonUtil.java @@ -0,0 +1,157 @@ +package xy.SpringBoot2NoSQL.utils; + +import org.redisson.Redisson; +import org.redisson.api.RAtomicLong; +import org.redisson.api.RBucket; +import org.redisson.api.RCountDownLatch; +import org.redisson.api.RDeque; +import org.redisson.api.RList; +import org.redisson.api.RLock; +import org.redisson.api.RMap; +import org.redisson.api.RQueue; +import org.redisson.api.RSet; +import org.redisson.api.RSortedSet; +import org.redisson.api.RTopic; +import org.redisson.api.RedissonClient; + +/** + * Redisson分布式操作类 + * @author 王昕 + * + */ +public class RedissonUtil { + + /** + * 关闭Redisson客户端连接 + * @param redisson + */ + public static void closeRedisson(RedissonClient redisson){ + redisson.shutdown(); + System.out.println("成功关闭Redis Client连接"); + } + + /** + * 获取字符串对象 + * @param redisson + * @param objectName + * @return + */ + public static RBucket getRBucket(RedissonClient redisson,String objectName){ + RBucket bucket=redisson.getBucket(objectName); + return bucket; + } + + /** + * 获取Map对象 + * @param redisson + * @param objectName + * @return + */ + public static RMap getRMap(RedissonClient redisson,String objectName){ + RMap map=redisson.getMap(objectName); + return map; + } + + /** + * 获取有序集合 + * @param redisson + * @param objectName + * @return + */ + public static RSortedSet getRSortedSet(RedissonClient redisson,String objectName){ + RSortedSet sortedSet=redisson.getSortedSet(objectName); + return sortedSet; + } + + /** + * 获取集合 + * @param redisson + * @param objectName + * @return + */ + public static RSet getRSet(RedissonClient redisson,String objectName){ + RSet rSet=redisson.getSet(objectName); + return rSet; + } + + /** + * 获取列表 + * @param redisson + * @param objectName + * @return + */ + public static RList getRList(RedissonClient redisson,String objectName){ + RList rList=redisson.getList(objectName); + return rList; + } + + /** + * 获取队列 + * @param redisson + * @param objectName + * @return + */ + public static RQueue getRQueue(RedissonClient redisson,String objectName){ + RQueue rQueue=redisson.getQueue(objectName); + return rQueue; + } + + /** + * 获取双端队列 + * @param redisson + * @param objectName + * @return + */ + public static RDeque getRDeque(RedissonClient redisson,String objectName){ + RDeque rDeque=redisson.getDeque(objectName); + return rDeque; + } + + + + /** + * 获取锁 + * @param redisson + * @param objectName + * @return + */ + public static RLock getRLock(RedissonClient redisson,String objectName){ + RLock rLock=redisson.getLock(objectName); + return rLock; + } + + /** + * 获取原子数 + * @param redisson + * @param objectName + * @return + */ + public static RAtomicLong getRAtomicLong(RedissonClient redisson,String objectName){ + RAtomicLong rAtomicLong=redisson.getAtomicLong(objectName); + return rAtomicLong; + } + + /** + * 获取记数锁 + * @param redisson + * @param objectName + * @return + */ + public static RCountDownLatch getRCountDownLatch(RedissonClient redisson,String objectName){ + RCountDownLatch rCountDownLatch=redisson.getCountDownLatch(objectName); + return rCountDownLatch; + } + + /** + * 获取消息的Topic + * @param redisson + * @param objectName + * @return + */ + public static RTopic getRTopic(RedissonClient redisson,String objectName){ + RTopic rTopic=redisson.getTopic(objectName); + return rTopic; + + } + +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..79c7f91 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,101 @@ +server.port=9092 +debug=true +spring.devtools.restart.exclude=static/** + +#spring.datasource.url=jdbc:mysql://localhost:3306/boot?useUnicode=true&zeroDateTimeBehavior=convertToNull&autoReconnect=true +#spring.datasource.username=root +#spring.datasource.password=mysql +#spring.datasource.driver-class-name=com.mysql.jdbc.Driver + +# MONGODB +spring.data.mongodb.host=127.0.0.1 +spring.data.mongodb.port=27017 +spring.data.mongodb.database=test + +#Cassandra +#spring.data.cassandra.keyspace-name=mydb +#spring.data.cassandra.contact-points=localhost +#spring.data.cassandra.port=9042 + +#Solr +spring.data.solr.host=http://localhost:8983/solr + +#Couchbase +#spring.couchbase.bootstrap-hosts=127.0.0.1 +#spring.couchbase.bucket.name=mydb +#spring.couchbase.bucket.password=123456 +#spring.data.couchbase.auto-index=true + +# Redis +# Redis\u6570\u636e\u5e93\u7d22\u5f15\uff08\u9ed8\u8ba4\u4e3a0\uff09 +spring.redis.database=0 +spring.redis.host=127.0.0.1 +spring.redis.port=6379 +#spring.redis.password=123 +# \u8fde\u63a5\u6c60\u6700\u5927\u8fde\u63a5\u6570\uff08\u4f7f\u7528\u8d1f\u503c\u8868\u793a\u6ca1\u6709\u9650\u5236\uff09 +spring.redis.pool.max-active=60 +# \u8fde\u63a5\u6c60\u4e2d\u7684\u6700\u5927\u7a7a\u95f2\u8fde\u63a5 +spring.redis.pool.max-idle=30 +# \u8fde\u63a5\u6c60\u6700\u5927\u963b\u585e\u7b49\u5f85\u65f6\u95f4\uff08\u4f7f\u7528\u8d1f\u503c\u8868\u793a\u6ca1\u6709\u9650\u5236\uff09 +spring.redis.pool.max-wait=-1 +# \u8fde\u63a5\u6c60\u4e2d\u7684\u6700\u5c0f\u7a7a\u95f2\u8fde\u63a5 +spring.redis.pool.min-idle=0 + +#redisson\u914d\u7f6e +#redis\u94fe\u63a5\u5730\u5740 +spring.redisson.address=redis://127.0.0.1:6379 +#\u5f53\u524d\u5904\u7406\u6838\u6570\u91cf * 2 +spring.redisson.thread=4 +#\u6307\u5b9a\u7f16\u89e3\u7801 +spring.redisson.codec=org.redisson.codec.JsonJacksonCodec +#\u6700\u5c0f\u7a7a\u95f2\u8fde\u63a5\u6570,\u9ed8\u8ba4\u503c:10,\u6700\u5c0f\u4fdd\u6301\u8fde\u63a5\u6570\uff08\u957f\u8fde\u63a5\uff09 +spring.redisson.connectionMinimumIdleSize=12 +#\u8fde\u63a5\u7a7a\u95f2\u8d85\u65f6\uff0c\u5355\u4f4d\uff1a\u6beb\u79d2 \u9ed8\u8ba410000;\u5f53\u524d\u8fde\u63a5\u6c60\u91cc\u7684\u8fde\u63a5\u6570\u91cf\u8d85\u8fc7\u4e86\u6700\u5c0f\u7a7a\u95f2\u8fde\u63a5\u6570\uff0c +#\u800c\u8fde\u63a5\u7a7a\u95f2\u65f6\u95f4\u8d85\u8fc7\u4e86\u8be5\u6570\u503c\uff0c\u8fd9\u4e9b\u8fde\u63a5\u5c06\u4f1a\u81ea\u52a8\u88ab\u5173\u95ed\uff0c\u5e76\u4ece\u8fde\u63a5\u6c60\u91cc\u53bb\u6389 +spring.redisson.idleConnectionTimeout=10000 +#ping\u8282\u70b9\u8d85\u65f6,\u5355\u4f4d\uff1a\u6beb\u79d2,\u9ed8\u8ba41000 +spring.redisson.pingTimeout=1000 +#\u8fde\u63a5\u7b49\u5f85\u8d85\u65f6,\u5355\u4f4d\uff1a\u6beb\u79d2,\u9ed8\u8ba410000 +spring.redisson.connectTimeout=10000 +#\u547d\u4ee4\u7b49\u5f85\u8d85\u65f6,\u5355\u4f4d\uff1a\u6beb\u79d2,\u9ed8\u8ba43000\uff1b\u7b49\u5f85\u8282\u70b9\u56de\u590d\u547d\u4ee4\u7684\u65f6\u95f4\u3002\u8be5\u65f6\u95f4\u4ece\u547d\u4ee4\u53d1\u9001\u6210\u529f\u65f6\u5f00\u59cb\u8ba1\u65f6 +spring.redisson.timeout=3000 +#\u547d\u4ee4\u5931\u8d25\u91cd\u8bd5\u6b21\u6570\uff0c\u9ed8\u8ba4\u503c:3 +spring.redisson.retryAttempts=2 +#\u547d\u4ee4\u91cd\u8bd5\u53d1\u9001\u65f6\u95f4\u95f4\u9694\uff0c\u5355\u4f4d\uff1a\u6beb\u79d2,\u9ed8\u8ba4\u503c:1500 +spring.redisson.retryInterval=1500 +#\u91cd\u65b0\u8fde\u63a5\u65f6\u95f4\u95f4\u9694\uff0c\u5355\u4f4d\uff1a\u6beb\u79d2,\u9ed8\u8ba4\u503c\uff1a3000;\u8fde\u63a5\u65ad\u5f00\u65f6\uff0c\u7b49\u5f85\u4e0e\u5176\u91cd\u65b0\u5efa\u7acb\u8fde\u63a5\u7684\u65f6\u95f4\u95f4\u9694 +spring.redisson.reconnectionTimeout=3000 +#\u6267\u884c\u5931\u8d25\u6700\u5927\u6b21\u6570, \u9ed8\u8ba4\u503c\uff1a3\uff1b\u5931\u8d25\u540e\u76f4\u5230 reconnectionTimeout\u8d85\u65f6\u4ee5\u540e\u518d\u6b21\u5c1d\u8bd5\u3002 +spring.redisson.failedAttempts=2 +#\u8eab\u4efd\u9a8c\u8bc1\u5bc6\u7801 +#spring.redisson.password= +#\u5355\u4e2a\u8fde\u63a5\u6700\u5927\u8ba2\u9605\u6570\u91cf\uff0c\u9ed8\u8ba4\u503c\uff1a5 +spring.redisson.subscriptionsPerConnection=5 +#\u5ba2\u6237\u7aef\u540d\u79f0 +#spring.redisson.clientName= +#\u53d1\u5e03\u548c\u8ba2\u9605\u8fde\u63a5\u7684\u6700\u5c0f\u7a7a\u95f2\u8fde\u63a5\u6570\uff0c\u9ed8\u8ba4\u503c\uff1a1\uff1bRedisson\u5185\u90e8\u7ecf\u5e38\u901a\u8fc7\u53d1\u5e03\u548c\u8ba2\u9605\u6765\u5b9e\u73b0\u8bb8\u591a\u529f\u80fd\u3002 +#\u957f\u671f\u4fdd\u6301\u4e00\u5b9a\u6570\u91cf\u7684\u53d1\u5e03\u8ba2\u9605\u8fde\u63a5\u662f\u5fc5\u987b\u7684 +spring.redisson.subscriptionConnectionMinimumIdleSize=1 +#\u53d1\u5e03\u548c\u8ba2\u9605\u8fde\u63a5\u6c60\u5927\u5c0f\uff0c\u9ed8\u8ba4\u503c\uff1a50 +spring.redisson.subscriptionConnectionPoolSize=50 +#\u8fde\u63a5\u6c60\u6700\u5927\u5bb9\u91cf\u3002\u9ed8\u8ba4\u503c\uff1a64\uff1b\u8fde\u63a5\u6c60\u7684\u8fde\u63a5\u6570\u91cf\u81ea\u52a8\u5f39\u6027\u4f38\u7f29 +spring.redisson.connectionPoolSize=64 +#\u6570\u636e\u5e93\u7f16\u53f7\uff0c\u9ed8\u8ba4\u503c\uff1a0 +spring.redisson.database=0 +#\u662f\u5426\u542f\u7528DNS\u76d1\u6d4b\uff0c\u9ed8\u8ba4\u503c\uff1afalse +spring.redisson.dnsMonitoring=false +#DNS\u76d1\u6d4b\u65f6\u95f4\u95f4\u9694\uff0c\u5355\u4f4d\uff1a\u6beb\u79d2\uff0c\u9ed8\u8ba4\u503c\uff1a5000 +spring.redisson.dnsMonitoringInterval=5000 + + +# elasticsearch +#\u8282\u70b9\u540d\u5b57\uff0c\u9ed8\u8ba4elasticsearch +spring.data.elasticsearch.cluster-name=elasticsearch +# \u8282\u70b9\u5730\u5740\uff0c\u591a\u4e2a\u8282\u70b9\u7528\u9017\u53f7\u9694\u5f00 +spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300 +#spring.data.elasticsearch.local=false +spring.data.elasticsearch.repositories.enable=true + +# ehcache +spring.cache.type=ehcache +spring.cache.ehcache.config=classpath:ehcache.xml \ No newline at end of file diff --git a/src/main/resources/cassandra.properties b/src/main/resources/cassandra.properties new file mode 100644 index 0000000..6b39d8e --- /dev/null +++ b/src/main/resources/cassandra.properties @@ -0,0 +1,3 @@ +cassandra.contactpoints=127.0.0.1 +cassandra.port=9042 +cassandra.keyspace=mydb \ No newline at end of file diff --git a/src/main/resources/couchdb.xml b/src/main/resources/couchdb.xml new file mode 100644 index 0000000..e7d752b --- /dev/null +++ b/src/main/resources/couchdb.xml @@ -0,0 +1,10 @@ + + + + + + \ No newline at end of file diff --git a/src/main/resources/ehcache.xml b/src/main/resources/ehcache.xml new file mode 100644 index 0000000..c645ed7 --- /dev/null +++ b/src/main/resources/ehcache.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/log4j2.xml b/src/main/resources/log4j2.xml new file mode 100644 index 0000000..00314e0 --- /dev/null +++ b/src/main/resources/log4j2.xml @@ -0,0 +1,61 @@ + + + + + /tmp/logs + /tmp/logs/7z + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/java/xy/SpringBoot2NoSQL/SpringBoot2NoSqlApplicationTests.java b/src/test/java/xy/SpringBoot2NoSQL/SpringBoot2NoSqlApplicationTests.java new file mode 100644 index 0000000..9e7aa1c --- /dev/null +++ b/src/test/java/xy/SpringBoot2NoSQL/SpringBoot2NoSqlApplicationTests.java @@ -0,0 +1,16 @@ +package xy.SpringBoot2NoSQL; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringBoot2NoSqlApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git "a/\350\204\232\346\234\254/Cassandra/\345\273\272\345\272\223\350\204\232\346\234\254.txt" "b/\350\204\232\346\234\254/Cassandra/\345\273\272\345\272\223\350\204\232\346\234\254.txt" new file mode 100644 index 0000000..b44c2d4 --- /dev/null +++ "b/\350\204\232\346\234\254/Cassandra/\345\273\272\345\272\223\350\204\232\346\234\254.txt" @@ -0,0 +1,15 @@ +创建keyspace : +create keyspace myDb with replication={'class':'SimpleStrategy', 'replication_factor':1}; + +建表: +use myDb; + +CREATE TABLE customer( + id text PRIMARY KEY, + firstname text, + lastname text, + age int +); + +建索引: +CREATE INDEX ON myDb.customer (firstname); \ No newline at end of file