CrazyAirhead

疯狂的傻瓜,傻瓜也疯狂——傻方能执著,疯狂才专注!

0%

数据操作 —— 操作 NoSQL

说明

一般的 Web 应用都会使用到 Redis 做缓存处理,也可能会用 ElasticSearch 做全文检索。所以这里主要介绍对这个两个数据中间件的使用。Monogo方面也有对应的插件,可以自行尝试。

创建模块

在 IDEA 中通过 File->New->Modules... 可以创建新的模块 demo-nosql,基础代码和配置可以从demo01中拷贝过来,或者自己手动创建。

修改依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
plugins {
id 'java'
id "io.freefair.lombok"
}

group = "com.example"
// 统一版本号
version "${demoVersion}"
description = "orm demo"

dependencies {
implementation platform(project(":demo-parent"))

implementation("org.noear:solon-web")
implementation("org.noear:solon-logging-logback")
implementation("org.noear:solon-openapi2-knife4j")
implementation("org.noear:solon-cache-jedis")
implementation("org.noear:esearchx")

annotationProcessor("org.mapstruct:mapstruct-processor:${mapstructVersion}")

testImplementation("org.noear:solon-test-junit5")
}


compileJava {
options.encoding = "UTF-8"
options.compilerArgs << "-parameters"
}

jar {
manifest {
attributes "Main-Class": "com.example.demo.orm.DemoOrmApp"
}

dependsOn(configurations.runtimeClasspath)

duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from(configurations.runtimeClasspath.collect {
if (it.isDirectory()) it else zipTree(it)
}) {
exclude 'META-INF/MANIFEST.MF'
exclude 'META-INF/*.SF'
exclude 'META-INF/*.DSA'
exclude 'META-INF/*.RSA'
}

def sourcesMain = sourceSets.main
sourcesMain.allSource.forEach { println("add from sources: ${it.name}") }
from(sourcesMain.output)
}

使用 Redis

增加依赖

build.gradle

1
2
3
dependencies {
implementation("org.noear:solon-cache-jedis")
}

修改配置

app.yml

1
2
3
4
5
6
7
8
9
10
11
12
# 配置数据源
demo:
redis:
driverType: redis #驱动类型
server: 127.0.0.1:6379
db: 0 #默认为 0,可不配置
password: porpoise-demo
keyHeader: porpoise-demo
enableMd5key: false
defSeconds: 600 #默认为 30,可不配置
idleConnectionTimeout: 10000
connectTimeout: 10000

增加配置类

RedisConfig

1
2
3
4
5
6
7
8
9
10
11
/**
* @author airhead
*/
@Configuration
public class RedisConfig {
@Bean(typed = true)
public RedisClient defaultClient(
@Inject("${demo.redis}") RedisClientSupplier redisClientSupplier) {
return redisClientSupplier.get();
}
}

增加 controller

Controller 非必须,只是方便测试。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* @author airhead
*/
@Controller
@Mapping("/redis")
@Api("redis")
public class RedisController {
@Inject private RedisClient redisClient;

@Mapping
@Get
@ApiOperation("获取key的值")
public String get(String key) {
return redisClient.openAndGet(session -> session.key(key).get());
}

@Mapping
@Post
@ApiOperation("设置key的值")
public Boolean set(String key, String value) {
redisClient.open(
session -> {
session.key(key).set(value);
});

return true;
}
}

验证

验证有很多种方式,这里通过 swagger 文档进行调用。浏览器输入 http://localhost:8080/doc.html

设置

img

获取

img

使用 ElasticSearch

增加依赖

build.gradle

1
2
3
4
dependencies {
// es 没有对应的插件,需要自己引入 esearchx
implementation("org.noear:esearchx")
}

修改配置

app.yml

1
2
3
4
5
6
# 配置数据源
demo:
es:
url: http://127.0.0.1:9200
username: root
password: 123456

增加配置类

EsConfig

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* @author airhead
*/
@Configuration
public class EsConfig {
/**
* url,username,password
*
* @param properties
* @return
*/
@Bean(name = "esContext", typed = true)
public EsContext esContext(@Inject("${demo.es}") Properties properties) {
return new EsContext(properties);
}
}

增加 entity

增加DemoEntity方便操作数据

1
2
3
4
5
6
7
8
/**
* @author airhead
*/
@Data
public class DemoEntity {
private String name;
private String code;
}

增加 controller

Controller 非必须,只是方便测试。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* @author airhead
*/
@Controller
@Mapping("/es")
@Api("es")
@Slf4j
public class EsController {
@Inject private EsContext esContext;

@Mapping
@Get
@ApiOperation("获取列表")
public List<DemoEntity> list() {
try {
EsData<DemoEntity> result = null;
result = esContext.indice("demo").selectList(DemoEntity.class);
return result.getList();
} catch (IOException e) {
log.error("add error", e);
throw new RuntimeException(e);
}
}

@Mapping
@Post
@ApiOperation("保存文档")
public Boolean add(@Body DemoEntity entity) {
try {
esContext.indice("demo").insert(entity);
} catch (IOException e) {
log.error("add error", e);
throw new RuntimeException(e);
}

return true;
}
}

验证

验证有很多种方式,这里通过 swagger 文档进行调用。浏览器输入 http://localhost:8080/doc.html

保存文档

img

获取文档列表

img

小结

Solon 通过简单的配置就可以操作 Redis 和 ElasticSearch ,对 NoSql 的支持还是挺完整的,更多的对数据的操作需要看具体的类库提供的接口。

完整代码可以从 https://gitee.com/CrazyAirhead/porpoise-demo 获取。

欢迎关注我的其它发布渠道