工具类
package com. zb. util;
import com. alibaba. otter. canal. client. CanalConnector;
import com. alibaba. otter. canal. client. CanalConnectors;
import com. alibaba. otter. canal. common. utils. AddressUtils;
import com. alibaba. otter. canal. protocol. CanalEntry;
import com. alibaba. otter. canal. protocol. Message;
import org. springframework. beans. factory. annotation. Autowired;
import org. springframework. stereotype. Component;
import org. springframework. web. client. RestTemplate;
import java. net. InetSocketAddress;
import java. util. HashSet;
import java. util. List;
import java. util. Set;
@Component
public class CanalUtil {
@Autowired
private RestTemplate restTemplate;
public void start ( ) {
CanalConnector connector = CanalConnectors. newSingleConnector ( new InetSocketAddress ( AddressUtils. getHostIp ( ) ,
11111 ) , "example" , "" , "" ) ;
int batchSize = 1000 ;
int emptyCount = 0 ;
try {
connector. connect ( ) ;
connector. subscribe ( ".*\\..*" ) ;
connector. rollback ( ) ;
int totalEmtryCount = 1200 ;
while ( emptyCount < totalEmtryCount) {
Message message = connector. getWithoutAck ( batchSize) ;
long batchId = message. getId ( ) ;
int size = message. getEntries ( ) . size ( ) ;
if ( batchId == - 1 || size == 0 ) {
emptyCount++ ;
System. out. println ( "empty count : " + emptyCount) ;
try {
Thread. sleep ( 1000 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
} else {
emptyCount = 0 ;
printEntry ( message. getEntries ( ) ) ;
}
connector. ack ( batchId) ;
}
System. out. println ( "empty too many times, exit" ) ;
} finally {
connector. disconnect ( ) ;
}
}
private void printEntry ( List< CanalEntry. Entry> entrys) {
for ( CanalEntry. Entry entry : entrys) {
if ( entry. getEntryType ( ) == CanalEntry. EntryType. TRANSACTIONBEGIN || entry. getEntryType ( ) == CanalEntry. EntryType. TRANSACTIONEND) {
continue ;
}
CanalEntry. RowChange rowChage = null;
try {
rowChage = CanalEntry. RowChange. parseFrom ( entry. getStoreValue ( ) ) ;
} catch ( Exception e) {
throw new RuntimeException ( "ERROR ## parser of eromanga-event has an error , data:" + entry. toString ( ) ,
e) ;
}
CanalEntry. EventType eventType = rowChage. getEventType ( ) ;
System. out. println ( String. format ( "================> binlog[%s:%s] , name[%s,%s] , eventType : %s" ,
entry. getHeader ( ) . getLogfileName ( ) , entry. getHeader ( ) . getLogfileOffset ( ) ,
entry. getHeader ( ) . getSchemaName ( ) , entry. getHeader ( ) . getTableName ( ) ,
eventType) ) ;
for ( CanalEntry. RowData rowData : rowChage. getRowDatasList ( ) ) {
if ( eventType == CanalEntry. EventType. DELETE) {
printColumn ( rowData. getBeforeColumnsList ( ) ) ;
} else if ( eventType == CanalEntry. EventType. INSERT) {
printColumn ( rowData. getAfterColumnsList ( ) ) ;
} else {
System. out. println ( "-------> before" ) ;
printColumn ( rowData. getBeforeColumnsList ( ) ) ;
System. out. println ( "-------> after" ) ;
printColumn ( rowData. getAfterColumnsList ( ) ) ;
}
updateContent ( rowData. getAfterColumnsList ( ) ) ;
}
}
}
public void updateContent ( List< CanalEntry. Column> columns) {
Set< Integer> categoryIds = new HashSet < Integer> ( ) ;
for ( CanalEntry. Column column : columns) {
if ( column. getName ( ) . equals ( "category_id" ) ) {
categoryIds. add ( Integer. parseInt ( column. getValue ( ) ) ) ;
}
}
for ( Integer categoryId : categoryIds) {
String json = restTemplate. getForObject ( "http://127.0.0.1:9090/lua3?gid=" + categoryId, String. class ) ;
System. out. println ( json) ;
}
}
private static void printColumn ( List< CanalEntry. Column> columns) {
for ( CanalEntry. Column column : columns) {
System. out. println ( column. getName ( ) + " : " + column. getValue ( ) + " update=" + column. getUpdated ( ) ) ;
}
}
}
启动类
package com. zb;
import com. zb. util. CanalUtil;
import org. springframework. boot. SpringApplication;
import org. springframework. boot. autoconfigure. SpringBootApplication;
import org. springframework. cloud. client. loadbalancer. LoadBalanced;
import org. springframework. context. ConfigurableApplicationContext;
import org. springframework. context. annotation. Bean;
import org. springframework. web. client. RestTemplate;
@SpringBootApplication
public class MyCanalTest {
public static void main ( String[ ] args) {
ConfigurableApplicationContext run = SpringApplication. run ( MyCanalTest. class , args) ;
CanalUtil bean = run. getBean ( CanalUtil. class ) ;
bean. start ( ) ;
}
@Bean
public RestTemplate restTemplate ( ) {
return new RestTemplate ( ) ;
}
}
pom.xml依赖
<?xml version="1.0" encoding="UTF-8"?>
< project xmlns = " http://maven.apache.org/POM/4.0.0"
xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance"
xsi: schemaLocation= " http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" >
< parent>
< artifactId> shop.main</ artifactId>
< groupId> org.example</ groupId>
< version> 1.0-SNAPSHOT</ version>
</ parent>
< modelVersion> 4.0.0</ modelVersion>
< artifactId> shop.canal</ artifactId>
< dependencies>
< dependency>
< groupId> org.springframework.boot</ groupId>
< artifactId> spring-boot-starter-web</ artifactId>
</ dependency>
< dependency>
< groupId> org.springframework.cloud</ groupId>
< artifactId> spring-cloud-starter-netflix-eureka-client</ artifactId>
</ dependency>
< dependency>
< groupId> org.springframework.cloud</ groupId>
< artifactId> spring-cloud-starter-openfeign</ artifactId>
</ dependency>
< dependency>
< groupId> com.alibaba.otter</ groupId>
< artifactId> canal.client</ artifactId>
< version> 1.1.2</ version>
</ dependency>
< dependency>
< groupId> com.alibaba.otter</ groupId>
< artifactId> canal.client-adapter</ artifactId>
< version> 1.1.2</ version>
< type> pom</ type>
</ dependency>
</ dependencies>
</ project>
配置Canal
#################################################
## mysql serverId , v1.0.26+ will autoGen
# canal.instance.mysql.slaveId=0
# enable gtid use true/false
canal.instance.gtidon=false
# position info
canal.instance.master.address=127.0.0.1:3306 //这里是端口
canal.instance.master.journal.name=
canal.instance.master.position=
canal.instance.master.timestamp=
canal.instance.master.gtid=
# rds oss binlog
canal.instance.rds.accesskey=
canal.instance.rds.secretkey=
canal.instance.rds.instanceId=
# table meta tsdb info
canal.instance.tsdb.enable=true
#canal.instance.tsdb.url=jdbc:mysql://127.0.0.1:3306/canal_tsdb
#canal.instance.tsdb.dbUsername=canal
#canal.instance.tsdb.dbPassword=canal
#canal.instance.standby.address =
#canal.instance.standby.journal.name =
#canal.instance.standby.position =
#canal.instance.standby.timestamp =
#canal.instance.standby.gtid=
# username/password
canal.instance.dbUsername=root //这里是用户名
canal.instance.dbPassword=ok //这里是密码
canal.instance.connectionCharset = UTF-8
# enable druid Decrypt database password
canal.instance.enableDruid=false
#canal.instance.pwdPublicKey=MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALK4BUxdDltRRE5/zXpVEVPUgunvscYFtEip3pmLlhrWpacX7y7GCMo2/JM6LeHmiiNdH1FWgGCpUfircSwlWKUCAwEAAQ==
# table regex
canal.instance.filter.regex=.*\\..*
# table black regex
canal.instance.filter.black.regex=
# table field filter(format: schema1.tableName1:field1/field2,schema2.tableName2:field1/field2)
#canal.instance.filter.field=test1.t_product:id/subject/keywords,test2.t_company:id/name/contact/ch
# table field black filter(format: schema1.tableName1:field1/field2,schema2.tableName2:field1/field2)
#canal.instance.filter.black.field=test1.t_product:subject/product_image,test2.t_company:id/name/contact/ch
# mq config
canal.mq.topic=example
# dynamic topic route by schema or table regex
#canal.mq.dynamicTopic=mytest1.user,mytest2\\..*,.*\\..*
canal.mq.partition=0
# hash partition config
#canal.mq.partitionsNum=3
#canal.mq.partitionHash=test.table:id^name,.*\\..*
#################################################
Cancal下载
链接: https://pan.baidu.com/s/1GjMyMkXTNYqr_cuoV2WULw
提取码: wptt
Lua配置
ngx. header. content_type= "application/json;charset=utf8"
local cjson = require ( "cjson" )
local mysql = require ( "resty.mysql" )
local uri_args = ngx. req. get_uri_args ( )
local id = uri_args[ "gid" ]
local db = mysql: new ( )
db: set_timeout ( 1000 )
local props = {
host = "127.0.0.1" ,
port = 3306 ,
database = "changgou_content" ,
user = "root" ,
password = "ok"
}
local res = db: connect ( props)
local select_sql = "select url,pic,title from tb_content where status ='1' and category_id=" .. id.. " order by sort_order"
res = db: query ( select_sql)
db: close ( )
local redis = require ( "resty.redis" )
local red = redis: new ( )
red: set_timeout ( 2000 )
local ip = "127.0.0.1"
local port = 6379
red: connect ( ip, port)
red: set ( "content_" .. id, cjson. encode ( res) )
red: close ( )
ngx. say ( "{flag:true}" )
openresty配置
留着自己看的,有幸被你看到很荣幸,不熟悉的可以给我留言