Titan Framework 内部接口与函数说明书

HTTP与网络

Spring风格的RestfulController

RestfulController 通用Restful API Controller

org.titan.framework.facade.controller.RestfulController

方法

参数

返回值

说明

getCreateCommand

arg0-ServiceName<String>

arg1-body<T>

Command

默认捕捉HTTP  POST请求

API结构示例:

https://{base_url}/{path}/{serviceName}

Body:json

getDeleteCommand

arg0-ServiceName<String>

arg1-id<String>

Command

默认捕捉HTTP  DELETE请求

API结构示例:

https://{base_url}/{path}/{serivceName}/{id}

body:空

getGetCommand

arg0-serviceName<String>

arg1-id<String>

Command

默认捕捉HTTP  GET请求

API结构示例:

https://{base_url}/{path}/{serviceName}/{id}

body:空

getPatchCommand

arg0-serviceName<String>

arg1-id<String>

arg2-body<String>

Command

默认捕捉HTTP  PATCH请求

API结构示例:

https://{base_url}/{path}/{serviceName}/{id}

body:json

getPutCommand

arg0-serviceName<String>

arg1-id<String>

arg2-body<String>

Command

默认捕捉HTTP  PUT请求

API结构示例:

http://{base_url}/{path}/{serviceName}/{id}

body:json

getQueryCommand

arg0-serviceName<String>

arg1-queryObject<Object>

Command

参自定义部分

 

RestfulController进行HTTP API Path注释同Spring风格

@RestController

@RequestMapping("/otp")

public class ADemoController extends RestfulController

 

TipsRestfulController各方法中的ServiceName可以用于区分API版本号,并且进行API版本兼容处理,例如https://{base_url}/login/v1  [POST]

 

完整的RestfulController实例

@RestController

@RequestMapping("/otp")

public class ADemoController extends RestfulController {

    @Override

    protected <T> Command<?> getCreateCommand(String service, T body) {

    try {

    System.out.println("service - " + service);

    String _body = (String) body;

    DemoAEntity entity = JsonParser.getObject(_body, DemoAEntity.class);

    return new Create<DemoAEntity>(entity);

        }catch(Exception e) {

        return null;

        }

    }

 

    @Override

    protected Command<?> getDeleteCommand(String service, String id) {

    DemoAEntity entity = new DemoAEntity();

    entity.setId(id);

        return new Delete<DemoAEntity>(entity);

    }

 

    @Override

    protected Command<?> getGetCommand(String arg0, String arg1) {

        return null;

    }

 

    @Override

    protected Command<?> getPatchCommand(String arg0, String arg1, String arg2) {

        return null;

    }

 

    @Override

    protected Command<?> getPutCommand(String arg0, String arg1, String arg2) {

        return null;

    }

 

    @Override

    protected Command<?> getQueryCommand(String arg0, Object arg1) {

    return null;

    }

}

QueryController 通用查询专用API Controller

–org.titan.framework.facade.controller.QueryController

方法

参数

返回值

说明

queryCommand

arg0-serviceName<String>

arg1-id<String>

Command.Query

默认步骤HTTP GET请求

API结构示例:

http://{base_url}/{path}/{serviceName}/{id}

body:空

完整的QueryController实例

@RestController

@RequestMapping("/cfind")

public class CDemoFindController extends QueryController {

 

    @Override

    protected Query<?> queryCommand(String serviceName, String id) {

        CDemoEntity entity = new CDemoEntity();

        entity.setName(serviceName);

        entity.setCode(id);

        return new Query<CDemoEntity>(entity);

    }

 

    @Inject

    DemoCFinder finder;

 

    @RequestMapping(method = { RequestMethod.GET }, headers = { "Accept=application/json" }, produces = {"application/json" })

    public ResponseEntity<Object> query() {

        Result result = finder.finWithPureSQL();

        return ResponseBuilder.instance().status(result.getStatusCode()).body(toJson(result.getEntities())).build();

    }

}

org.titan.framework.facade.controller的自定义方式

Titan FrameworkController的自定义方式类似Spring风格,如果曾经使用过SpringMVC的用户将会很快上手。

@RequestMapping(method = { RequestMethod.GET }, headers = { "Accept=application/json" }, produces = {"application/json" })

@Override

protected Command<?> getQueryCommand(String arg0, Object arg1) {

   return null;

}

CommandHandler&Command 通用指令模型

–org.titan.framework.facade.application.CommandHandler

–org.titan.framework.facade.application.Command

Titan Framework中采用如下逻辑进行Command捕捉与传递。

第一步:Controllerreturn一个CommandTitanController基类;

第二步:TitanController基类中将会完成Command类型的识别与自动匹配;

第三步:TitanCommand发送到对应的应用层CommandHandler(注意:必须有@CmdHandler注释)

 

一个简单的CommandHandler案例如下:

@CmdHandler

public class DemoACreateHandler implements CommandHandler<Create<DemoAEntity>> {

    @Override

    public Result handle(Create<DemoAEntity> cmd) {

        DemoAEntity entity = cmd.getEntity();

        System.out.println(entity.getName() + "," + entity.getText());

        HelloWorldEntity mEntity = new HelloWorldEntity();

        Result result = Result.create(true, mEntity);

        return result;

    }

}

Command&Command类型

CommandTitan框架中的指令单元,用来关联Controller与对应的具体处理逻辑,实现Controller与逻辑处理的解耦。Titan Framework为用户预置了下面这些Command类型,大家可以直接使用。

类型

说明

Command.Create

Create类型的Command

Command.Delete

Delete类型的Command

Command.Error

Error类型的Command

Command.Get

Get类型的Command

Command.Patch

Patch类型的Command

Command.Query

Query类型的Command

Command.Put

Put类型的Command

当然,大家也可以通过实现Command接口来自定义自己的Command。对于自定义CommandTitan Framework同样提供自动匹配支持。

Command中实现了以下默认方法:

方法

参数

返回值

说明

getCache

String

Object

调取Command缓存中的全局数据

putCache

<String,Object>

Void

将一个数据放入Command缓存中

getEntity

Void

DataEntity

获取绑定在Command中的DataEntity

getEntityClassT

Void

Class

获取绑定在CommandDataEntity的具体类型

ResultResult的使用

ResultTitan Framework中通用返回值的包装类,通过Result可以直接获取结果、状态、错误信息等。 

Result有以下构造方式:

方式

参数

说明

Result.create(boolean,dataEntity)

boolean-成功状态标志位

dataEntity-携带的具体数据

可以用于微服务之间的返回;

可以用于CommandHandlerAPI层的返回,此时dataEntity将会作为HTTP Response中的json body,此时http code默认为200;

Result.create(boolean, int,dataEntity)

boolean-成功状态标志位

Int-http状态码

dataEntity-携带的具体数据

可以用于微服务之间的返回;

可以用于CommandHandlerAPI层的返回,此时dataEntity将会作为HTTP Response中的json body,此时http code为输入的int参数

Result.create(boolean,String,String)

boolean-成功状态标志位

String-错误码

String-错误信息

 

Result.create(boolean,int,String,String)

boolean-成功状态标志位

int-状态码

String-错误码

String-错误消息

 

Titan内置的Result信号类型,可以快速构建对应的result

类型

说明

Result.Status.Acceptable

远端微服务接受某项请求;返回码202

Result.Status.AvailableNotEnough

支付模块中可用金额不足;返回码513

Result.Status.Conflict

数据冲突;返回码409

Result.Status.Continue

串型处理同步;返回码100

Result.Status.Fault

错误反馈;返回码 ;内部使用

Result.Status.Forbidden

禁止操作;返回码 403

Result.Status.Found

数据库中存在指定数据;返回码 302

Result.Status.Gone

定向数据已销毁;返回码 410

Result.Status.MethodNotAllowed

微服务操作权限不足;返回码 405

Result.Status.NoContent

空数据内容提示;返回码 204

Result.Status.NoFound

数据库中无指定数据;返回码 404

Result.Status.NotAcceptable

微服务参数错误/微服务拒绝远程调用;返回码 406

Result.Status.Ok

成功;返回码 ;内部使用

Result.Status.Processing

特定事务处理中;返回码 102

Result.Status.RequiredPayment

待支付标志;返回码 402

Result.Status.ServerError

服务器内部错误;返回码 500

Result.Status.TimeOut

超时;返回码 408

Result.Status.Unauthorized

Token无效;返回码 401

Result的方法:

方法

参数

返回值

说明

getEntity

Void

DataEntity

获取Result中绑定的DataEntity

getErrors

Void

String

获取错误码

getErrorMessage

Void

String

获取错误信息

getStatusCode

Void

int

获取状态码

微服务远程调度

Publish&EventHandler

–org.titan.framework.facade.kit.Publish

–org.titan.framework.facade.event.EventHandler

PublishTitan Framework的微服务远程调用入口,用于有针对性地向远程服务发起请求事件。

Publish有以下方法:

方法

参数

返回值

说明

Pipto

ParallelContext

Actor

void

同时请求多个微服务同时响应一个事件;Titan Framework高阶版本特性;

Send

ParallelContext

Result

请求一个远程微服务响应事件,并异步等待回复

Send

LocalContext

Result

请求一个本地微服务响应事件,并异步等待回复

Tell

PublishContext

void

告知一个远程微服务响应事件,但是不等待任何回复

Proxy

TransportContext,

Actor

Result

请求某个远程微服务作为代理;Titan Framework高阶版本特性;

Publish的使用示例:

Send模式(Remote

@CmdHandler

public class DemoACreateHandler implements CommandHandler<Create<DemoAEntity>> {

 

    @Override

    public Result handle(Create<DemoAEntity> cmd) {

        DemoAEntity entity = cmd.getEntity();

        System.out.println("vvvvv");

        System.out.println(entity.getName() + "," + entity.getText());

        Result result = Publish.Send(Ways.Remote(Paths.DemoB.service.getServerName(), new DemoACreateEvent())).Retry();

        return result;

    }

 

}

Send模式(Local

@CmdHandler

public class CreateHandler implements CommandHandler<Create<CDemoEntity>> {

 

    @Override

    public Result handle(Create<CDemoEntity> cmd) {

        Publish.Send(Ways.Local(DemoCEvent.create(cmd.getEntity()))).Retry();

        return Result.Status.Ok;

    }

 

}

public class DemoCEvent extends AppEvent {

    private static final long serialVersionUID = 854614362533549305L;

    static public enum Status {

        Create(1), Update(2), Delete(3);

        final int value;

        Status(int value) {

            this.value = value;

        }

    }

 

    public final Status status;

    Object data;

    DemoCEvent(Status status) {

        this.status = status;

    }

    <T> DemoCEvent init(T data) {

        this.data = data;

        return this;

    }

 

    @SuppressWarnings("unchecked")

    public <T> Optional<T> getData() {

        return (Optional<T>) Optional.ofNullable(data);

    }

 

    static public <T> DemoCEvent create(T entity) {

        return new DemoCEvent(Status.Create).init(entity);

    }

 

    static public <T> DemoCEvent update(T entity) {

        return new DemoCEvent(Status.Update).init(entity);

    }

 

    static public <T> DemoCEvent delete(T entity) {

        return new DemoCEvent(Status.Delete).init(entity);

    }

 

}

Publish相对应的是其他微服务的EventHandlerPublish发送EventEventHandler接收响应Event

EventHandlerCommandHandler类似,通过Event的类型来进行远程匹配。

EventHandler使用示例:

@EvtHandler(Role = "demo", Service = "c")

public class DemoCEventHandler implements EventHandler<DemoCEvent> {

    @Inject

    DemoCRespository respository;

 

    @Override

    public void handle(DemoCEvent event) {

        System.out.println("-- demo.c-- event... ");

        Result result = Result.Status.Ok;

        switch (event.status) {

        case Create:

            result = onCreate(event.getData());

            break;

        case Update:

            result = onUpdate(event.getData());

            break;

        case Delete:

            result = onDelete(event.getData());

            break;

        default:

            break;

        }

        Feedback.content(event, result);

    }

 

    Result onCreate(Optional<CDemoEntity> optional) {

        return optional.map(entity -> {

            entity.setId(AggregateId.generate().getId());

            return respository.create(entity);

        }).orElse(Result.Status.Fault);

    }

 

    Result onUpdate(Optional<CDemoEntity> opt) {

        return opt.map(entity -> {

            // -- maybe validate entity

            return respository.update(entity);

        }).orElse(Result.Status.Fault);

    }

 

    Result onDelete(Optional<CDemoEntity> opt) {

        return opt.map(entity -> {

            return respository.delete(entity);

        }).orElse(Result.Status.Fault);

    }

 

}

EventHandler中关键方法为Feedback.content(),用来通过非阻断的方式将处理结果返回至调用者。

方法

参数

返回值

说明

Feedback.content

AppEvent-远端Event

Result-返回结果

Void

通过非阻断式方式进行远程反馈

Tips:自定义AppEventResult中都可以携带数据进行返回,Titan官方不建议返回数据过大,如果需要返回大量数据或者二进制流数据,可以通过Event驱动加MessageQueue的方式进行处理。

 

数据库&消息队列支持

Titan FrameworkMySqlMongoDBRedis提供直接支持。

Titan FrameworkMySql支持

TitanMysql的对接包括以下三部分:

–conf包下的mysql.properties

–spring包下的application-dynamic-ds-context.xmlapplication-context.xml

基于Titan SpringMysqlRepositorySpringMysqlFindRepository的功能模块

其中SpringMysqlRepository是数据库写模型,SpringMysqlFindRepository是数据库读模型。

SpringMySqlRepository用法如下:

@Repository

public class DemoCRespository extends SpringMysqlRepository<CDemoEntity> {

 

    @Override

    protected String getTableName() {

        return "testentity";

    }

 

}

@EvtHandler(Role = "demo", Service = "c")

public class DemoCEventHandler implements EventHandler<DemoCEvent> {

 

    @Inject

    DemoCRespository respository;

 

    @Override

    public void handle(DemoCEvent event) {

 

        System.out.println("-- demo.c-- event... ");

        Result result = Result.Status.Ok;

 

        switch (event.status) {

        case Create:

            result = onCreate(event.getData());

            break;

        case Update:

            result = onUpdate(event.getData());

            break;

        case Delete:

            result = onDelete(event.getData());

            break;

        default:

            break;

        }

        

        Feedback.content(event, result);

    }

 

    Result onCreate(Optional<CDemoEntity> optional) {

        return optional.map(entity -> {

            entity.setId(AggregateId.generate().getId());

            return respository.create(entity);

        }).orElse(Result.Status.Fault);

    }

 

    Result onUpdate(Optional<CDemoEntity> opt) {

        return opt.map(entity -> {

            // -- maybe validate entity

            return respository.update(entity);

        }).orElse(Result.Status.Fault);

    }

 

    Result onDelete(Optional<CDemoEntity> opt) {

        return opt.map(entity -> {

            return respository.delete(entity);

        }).orElse(Result.Status.Fault);

    }

SpringMysqlRepository中包含以下方法:

方法

参数

返回值

说明

Create

DataEntity

Result

创建

Update

DataEntity

Result

更新

Delete

DateEntity

Result

删除

Load

String-Id

Result

读取

UfwCreate

DataEntity

Void

原子创建事务

UfwUpdate

DataEntity

Void

原子更新事务

UfwDelete

DataEntity

Void

原子删除事务

SpringMysqlFindRepository示例如下:

@Repository

public class DemoCFinder extends SpringMysqlFindRepository<CDemoEntity> {

 

    @Override

    protected String getTableName() {

        return "testentity";

    }

 

    // pure SQL fetch

    public Result finWithPureSQL() {

        String sql = " select * from " + getTableName();

        List<Map<String, Object>> records = Optional.ofNullable(DSLContext().fetch(sql)).map(list -> {

            return DSLUtility.convertList(list);

        }).orElse(null);

        return Optional.ofNullable(records).map(ls -> {

            return Result.create(true, ls);

        }).orElse(Result.Status.NoFound);

    }

 

}

mysql.properties示例如下:

#Database Configuration

df.db.driver=com.mysql.cj.jdbc.Driver

# for master

master.db.url=jdbc:mysql://127.0.0.1:3306/bentest?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=true

master.db.username=

master.db.password=

# for slave

slave.db.url=jdbc:mysql://127.0.0.1:3306/bentest?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=true

slave.db.username=

slave.db.password=

#jOOQ Configuration

jooq.sql.dialect=MYSQL

 

#useUnicode=true&characterEncoding=UTF-8&useSSL=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC

application-context.xml示例如下:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="

        http://www.springframework.org/schema/beans     

        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd

        http://www.springframework.org/schema/context

        http://www.springframework.org/schema/context/spring-context-3.1.xsd

        http://www.springframework.org/schema/mvc

        http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

<context:annotation-config />

<context:component-scan base-package="org.titan.framework org.titan.loginRegister" />

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

<property name="locations">

<list>

    <value>file:**/conf/mysql.properties</value>

<value>file:**/conf/redis.properties</value>

</list>

</property>

<property name="ignoreUnresolvablePlaceholders" value="true" />

</bean>

<import resource="application-redis-context.xml" />

<import resource="application-mongoDB-context.xml" />

</beans>

application-dynamic-ds-context.xml示例如下:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"

xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"

xmlns:jdbc="http://www.springframework.org/schema/jdbc"

xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-4.1.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-4.1.xsd   

    http://www.springframework.org/schema/tx

    http://www.springframework.org/schema/tx/spring-tx-4.1.xsd

    http://www.springframework.org/schema/context

    http://www.springframework.org/schema/context/spring-context-4.1.xsd

    http://www.springframework.org/schema/jdbc

    http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd">

<bean id="dsMaster" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close">

<property name="driverClass" value="${df.db.driver}" />

<property name="jdbcUrl" value="${master.db.url}" />

<property name="username" value="${master.db.username}" />

<property name="password" value="${master.db.password}" />

</bean>

<bean id="dsSlave" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close">

<property name="driverClass" value="${df.db.driver}" />

<property name="jdbcUrl" value="${slave.db.url}" />

<property name="username" value="${slave.db.username}" />

<property name="password" value="${slave.db.password}" />

</bean>

<bean id="dataSource" class="org.titan.framework.core.integration.sql.storage.DynamicDataSource">

<property name="targetDataSources">

<map key-type="org.titan.framework.core.integration.sql.storage.DataSourceType">

<entry key="dsDefault" value-ref="dsMaster"></entry>

</map>

</property>

<property name="defaultTargetDataSource" ref="dsMaster"></property>

</bean>

<bean id="lazyConnectionDataSource" class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy">

<constructor-arg ref="dataSource" />

</bean>

<bean id="transactionAwareDataSource" class="org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy">

<constructor-arg ref="lazyConnectionDataSource" />

</bean>

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

<property name="dataSource" ref="lazyConnectionDataSource" />

</bean>

 

<bean class="org.jooq.impl.DataSourceConnectionProvider" name="connectionProvider">

<constructor-arg ref="transactionAwareDataSource" />

</bean>

<bean id="dslContext" class="org.jooq.impl.DefaultDSLContext">

<constructor-arg ref="jooqConfig" />

</bean>

<bean id="exceptionTranslator"

class="org.titan.framework.core.integration.sql.transaction.ExceptionTranslator" />

<bean class="org.jooq.impl.DefaultConfiguration" name="jooqConfig">

<property name="SQLDialect">

<value type="org.jooq.SQLDialect">${jooq.sql.dialect}</value>

</property>

<property name="connectionProvider" ref="connectionProvider" />

<property name="executeListenerProvider">

<array>

<bean class="org.jooq.impl.DefaultExecuteListenerProvider">

<constructor-arg index="0" ref="exceptionTranslator" />

</bean>

</array>

</property>

</bean>

</beans>

Titan FrameworkMongoDB支持

TitanMongoDB的对接包括以下两部分:

–spring包下的application-mongoDB-context.xml、application-context.xml

–conf包下的mongoDB.properties

基于Titan MongodbRepository的功能模块

其中需要实现StorageDataProcessor.Mongo

MongodbRepository用法如下:

@Repository

public class MongodbRepository implements StorageDataProcessor.Mongo {

@Override

public MongoDBConverter extConverter() {

// TODO Auto-generated method stub

return null;

}

public List<User> queryList(User user) {

Curd crud = curd();

List<User> list = new ArrayList<User>();

    list = crud.queryByCondition(MongoDBQueryCondition.Condition(query -> {

        query.Table(User.class.getSimpleName(), User.class).Condition("Phone", user.getPhone());

    }));

    return list ;

}

}

application-mongoDB-context.xml示例如下:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"

    xmlns:mongo="http://www.springframework.org/schema/data/mongo"

    xsi:schemaLocation="http://www.springframework.org/schema/beans

               http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

               http://www.springframework.org/schema/data/mongo

            http://www.springframework.org/schema/data/mongo/spring-mongo.xsd">

    <mongo:mongo-client host="${mongo.host}" port="${mongo.port}" id="mongo">  

       <mongo:client-options write-concern="SAFE"/>  

    </mongo:mongo-client> 

    <mongo:db-factory  id="mongoDbFactory" dbname="${mongo.dbname}" mongo-ref="mongo" />  

 

    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">  

       <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />  

    </bean>   

 

</beans>

application-context.xml示例如下:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="

        http://www.springframework.org/schema/beans     

        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd

        http://www.springframework.org/schema/context

        http://www.springframework.org/schema/context/spring-context-3.1.xsd

        http://www.springframework.org/schema/mvc

        http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

<context:annotation-config />

<context:component-scan base-package="org.titan.framework org.titan.loginRegister" />

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

<property name="locations">

<list>

    <value>file:**/conf/mysql.properties</value>

<value>file:**/conf/redis.properties</value>

                <value>file:**/conf/mongoDB.properties</value>

</list>

</property>

<property name="ignoreUnresolvablePlaceholders" value="true" />

</bean>

<!-- <import resource="application-dynamic-ds-context.xml" /> -->

<import resource="application-redis-context.xml" />

<import resource="application-mongoDB-context.xml" />

</beans>

mongoDB.properties示例如下:

mongo.host=127.0.0.1

mongo.port=27017

mongo.dbname=loginRegister

Titan FrameworkRedis支持

TitanMysql的对接包括以下三部分:

–spring包下的application-redis-context.xml、application-context.xml

–conf包下的redis.properties

基于Titan ShardedJedisPool的功能模块

ShardedJedisPool用法如下:

@EvtHandler(Role = "loginRegister", Service = "b")

public class CreateOtpEventHandler implements EventHandler<OtpCreateEvent> {

 

@Resource(name = "shardedJedisPool")

private ShardedJedisPool shardedJedisPool;

@Override

public void handle(OtpCreateEvent event) {

String phone = event.getPhone();

ShardedJedis jedis = null;

try {

jedis = shardedJedisPool.getResource();

jedis.setex(phone, 10*60, phone);

} finally {

if (jedis != null) {

jedis.close();

}

}

return;

 

}

 

}

application-redis-context.xml用法如下:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:jdbc="http://www.springframework.org/schema/jdbc"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd

            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd

            http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd">

 

<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">

 

<property name="maxIdle" value="${jedisPool.maxIdle}" />

<property name="minIdle" value="${jedisPool.minIdle}" />

 

<property name="testOnBorrow" value="${jedisPool.testOnBorrow}" />

<property name="testOnReturn" value="${jedisPool.testOnReturn}" />

 

<property name="timeBetweenEvictionRunsMillis" value="${jedisPool.timeBetweenEvictionRunsMillis}" />

<property name="testWhileIdle" value="${jedisPool.testWhileIdle}" />

<property name="minEvictableIdleTimeMillis" value="${jedisPool.minEvictableIdleTimeMillis}" />

<property name="softMinEvictableIdleTimeMillis" value="${jedisPool.softMinEvictableIdleTimeMillis}" />

<property name="numTestsPerEvictionRun" value="${jedisPool.numTestsPerEvictionRun}" />

</bean>

 

 

<bean id="shard-node-01" class="redis.clients.jedis.JedisShardInfo">

<constructor-arg index="0" value="${jedisPool.shard1.host}" />

<constructor-arg index="1" type="int" value="${jedisPool.shard1.port}" />

<property name="password" value="${jedisPool.shard1.password}" />

</bean>

 

<bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool">

<constructor-arg index="0" ref="jedisPoolConfig" />

<constructor-arg index="1">

<list>

<ref bean="shard-node-01" />

</list>

</constructor-arg>

</bean>

</beans>

application-context.xml用法如下:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="

        http://www.springframework.org/schema/beans     

        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd

        http://www.springframework.org/schema/context

        http://www.springframework.org/schema/context/spring-context-3.1.xsd

        http://www.springframework.org/schema/mvc

        http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

<context:annotation-config />

<context:component-scan base-package="org.titan.framework org.titan.loginRegister" />

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

<property name="locations">

<list>

    <value>file:**/conf/mysql.properties</value>

<value>file:**/conf/redis.properties</value>

</list>

</property>

<property name="ignoreUnresolvablePlaceholders" value="true" />

</bean>

<import resource="application-redis-context.xml" />

<import resource="application-mongoDB-context.xml" />

</beans>

redis.properties用法如下:

#最大分配的对象数  

jedisPool.maxActive=20  

 

#最大能够保持idel状态的对象数  

jedisPool.maxIdle=20  

 

#最小能够保持idel状态的对象数  

jedisPool.minIdle=10  

 

#当池内没有返回对象时,最大等待时间  

jedisPool.maxWait=-1  

 

#当调用borrow Object方法时,是否进行有效性检查  

#指明是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个

jedisPool.testOnBorrow=true  

  

#returnpool时,是否提前进行validate操作

jedisPool.testOnReturn =false

 

#表示当pool中的jedis实例都被allocated完时,pool要采取的操作;

#默认有三种WHEN_EXHAUSTED_FAIL(表示无jedis实例时,直接抛出NoSuchElementException)、

#WHEN_EXHAUSTED_BLOCK(则表示阻塞住,或者达到maxWait时抛出JedisConnectionException)、

#WHEN_EXHAUSTED_GROW(则表示新建一个jedis实例,也就说设置的maxActive无用)

jedisPool.whenExhaustedAction=1 

 

#表示idle object evitor两次扫描之间要sleep的毫秒数;

jedisPool.timeBetweenEvictionRunsMillis = 100000

 

#如果为true,表示有一个idle object evitor线程对idle object进行扫描,如果validate失败,此object会被从pooldrop掉;

#这一项只有在timeBetweenEvictionRunsMillis大于0时才有意义; 

jedisPool.testWhileIdle=true

 

#表示一个对象至少停留在idle状态的最短时间,然后才能被idle object evitor扫描并驱逐;

#这一项只有在timeBetweenEvictionRunsMillis大于0时才有意义

jedisPool.minEvictableIdleTimeMillis=300000 

 

#minEvictableIdleTimeMillis基础上,加入了至少minIdle个对象已经在pool里面了。

#如果为-1evicted不会根据idle time驱逐任何对象。如果minEvictableIdleTimeMillis>0,则此项设置无意义,

#且只有在timeBetweenEvictionRunsMillis大于0时才有意义

jedisPool.softMinEvictableIdleTimeMillis = -1 

 

#表示idle object evitor每次扫描的最多的对象数

jedisPool.numTestsPerEvictionRun = 50  

 

#borrowObject返回对象时,是采用DEFAULT_LIFOlast in first out,即类似cache的最频繁使用队列),如果为False,则表示FIFO队列

jedisPool.lifo = true

#IP  

jedisPool.shard1.host=127.0.0.1

#jedisPool.shard1.host=192.168.10.135

#jedisPool.shard1.host=139.196.6.164

#139.196.6.164

 

 

#Port  

jedisPool.shard1.port=6379

#jedisPool.shard1.port=2323

#jedisPool.shard1.port=32770

#32775

#

 

#password

jedisPool.shard1.password=test

 

#客户端超时时间单位是毫秒

redis.timeout=100000

 

#name

redis.name=queue

 

#database

redis.database=2

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值