当前位置:网站首页>Minimalist thrift+consumer
Minimalist thrift+consumer
2022-07-29 01:46:00 【In the misty rain of the Pavilion】
Minimalist Edition thrift+consul Solution
One 、 Make complaints
I wrote an issue on this topic before , Then it was copied intact by a website outside the wall … But the problem is that there was a problem with the last issue of the code , I deleted it and prepared to rewrite it . I hope the plagiarists can update this article synchronously …
Two 、 Get ready
docker Make one consul
docker pull docker.io/consul
then
docker run -d --name test_consul -p 8500:8500 docker.io/consul
service provider
First compile a Hello.java Of thrift service
idl as follows :
namespace java com.yanyu.service.rpc
service Hello{
string sayHello(1:string param)
}
function
thrift -r -gen java Hello.thrift
It can generate Hello.java, This is our service
And then create a new one maven project
Depends on the following :
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.apache.thrift</groupId>
<artifactId>libthrift</artifactId>
<version>0.10.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
</dependencies>
among springboot Version is 2.4.1,cloud Version is 2020.0.1
To configure
server:
port: 8003
spring:
application:
name: consul-thrift-provider
cloud:
consul:
port: 8500
host: localhost
discovery:
service-name: ${
spring.application.name}
rpc:
maxThreads: 10
minThreads: 1
delay: 10
thrift:
port: 8013
name: thrift-service
Officially start writing code
starter
@SpringBootApplication
@EnableDiscoveryClient
public class AppPro {
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(AppPro.class, args);
ThriftServer thriftServer = run.getBean(ThriftServer.class);
thriftServer.start();
}
}
among ThriftServer Not yet , Write the following , Don't rush to be popular .
Tool class
Register parameter entity class :
/** * desc Register parameter entity class */
@Data
@Builder(toBuilder = true)
public class RegisterParameter {
private String Name;
private String Id;
private String[] Tags;
private String Address;
private int Port;
}
Register machine :
@Component
public class ConsulRegister {
public static final String path = "/v1/agent/service/register";
@Resource
private RestTemplate restTemplate;
public void registe(RegisterParameter registerParameter, String consulAddress){
restTemplate.put(consulAddress, JSON.toJSONString(registerParameter));
}
}
The overall idea is to send put Request to consul Interface for registration . Here we need to define restTemplate, Otherwise, we can't inject :
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
Service implementation
@Service
public class HelloServiceImpl implements Hello.Iface {
@Override
public String sayHello(String param) throws TException {
return String.format("hello: %s, it's my provider!", param);
}
}
register
@Slf4j
@Component
public class ThriftServer {
@Value("${spring.cloud.consul.host}")
private String consulHost;
@Value("${spring.cloud.consul.port}")
private int consulPort;
/** * thrift Service port */
@Value("${rpc.thrift.port}")
private int port;
@Value("${rpc.thrift.name}")
/** * thrift service name */
private String thriftName;
@Value("${rpc.minThreads}")
private int minThreads;
@Value("${rpc.maxThreads}")
private int maxThreads;
/** * thrift Address of service */
private final String hostIp = InetAddress.getLocalHost().getHostAddress();
@Resource
private ConsulRegister consulRegister;
// Agreement factory
private TBinaryProtocol.Factory protocolFactory;
// Transmission plant
private TTransportFactory transportFactory;
/** * Classes that actually provide services */
@Resource
private HelloServiceImpl helloService;
public ThriftServer() throws UnknownHostException {
}
public void init() {
protocolFactory = new TBinaryProtocol.Factory();
transportFactory = new TTransportFactory();
}
public void start() {
Hello.Processor processor = new Hello.Processor<Hello.Iface>(helloService);
init();
try {
TServerTransport transport = new TServerSocket(port);
TThreadPoolServer.Args tArgs = new TThreadPoolServer.Args(transport);
tArgs.processor(processor);
tArgs.protocolFactory(protocolFactory);
tArgs.transportFactory(transportFactory);
tArgs.minWorkerThreads(minThreads);
tArgs.maxWorkerThreads(maxThreads);
TServer server = new TThreadPoolServer(tArgs);
log.info("thrift Service started successfully , Address =http://{}", hostIp + ":" + port);
String consulInfo = String.format("http://%s:%d%s", consulHost, consulPort, ConsulRegister.path);
log.info(String.format("consulInfo is %s", consulInfo));
consulRegister.registe(
RegisterParameter.builder().Name(thriftName).Port(port).Address(hostIp).Id(thriftName + "-" + port)
.build(), consulInfo);
server.serve();
} catch (Exception e) {
log.error(" Service startup failed ,", e);
}
}
}
Start it up , You can see :
No mistake is success
Consumer
rely on
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.apache.thrift</groupId>
<artifactId>libthrift</artifactId>
<version>0.10.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
</dependencies>
The configuration file
server:
port: 9003
spring:
application:
name: consul-thrift-consumer
cloud:
consul:
port: 8500
host: localhost
discovery:
service-name: ${
spring.application.name}
rpc:
maxThreads: 10
minThreads: 1
delay: 10
thrift:
port: 8013
host: localhost
starter
@SpringBootApplication
@EnableDiscoveryClient
public class ConApp {
public static void main(String[] args) {
SpringApplication.run(ConApp.class, args);
}
}
Start
Define service entity classes
@Data
public class ServiceEntity {
String Id;
String Service;
String[] Tags;
Meta Meta;
int Port;
String Address;
TaggedAddresses TaggedAddresses;
Weights Weights;
boolean EnableTagOverride;
String Datacenter;
}
@Data
class Meta {
boolean secure;
}
@Data
class TaggedAddresses{
lan_ipv4 lan_ipv4;
wan_ipv4 wan_ipv4;
}
@Data
class lan_ipv4{
String Address;
int Port;
}
@Data
class wan_ipv4{
String Address;
int Port;
}
@Data
class Weights{
int Passing;
int Warning;
}
Definition restTemplate
ditto
Define a class that reads all services
In fact, you don't need to read all services , It should only be the one that serves , But I'm too lazy to do it …
@Service
@Slf4j
public class GetAllConsulService {
@Resource
private RestTemplate restTemplate;
public Map<String, ServiceEntity> allServiceJson(){
JSONObject maps = restTemplate.getForObject("http://localhost:8500/v1/agent/services", JSONObject.class);
Map<String, ServiceEntity> res = new HashMap<>();
for(String key : maps.keySet()){
res.put(key, JSON.parseObject(JSON.toJSONString(maps.getJSONObject(key)), ServiceEntity.class));
}
return res;
}
}
This realization is a little ugly , But functional starfish
call Thrift Of Client
public class HelloClient {
private Hello.Client helloService;
private TBinaryProtocol protocol;
private TSocket transport;
private String host;
private int port;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public void init(){
transport = new TSocket(host, port);
protocol = new TBinaryProtocol(transport);
helloService = new Hello.Client(protocol);
}
public Hello.Client getHelloService(){
return helloService;
}
public void open() throws TTransportException {
transport.open();
}
public void close(){
transport.close();
}
}
hold HelloClient Trusteeship in Spring:
@Component
public class HelloConfig {
@Resource
private GetAllConsulService getAllConsulService;
@Bean(initMethod = "init")
public HelloClient helloClient(){
HelloClient helloClient = new HelloClient();
helloClient.setHost(getAllConsulService.allServiceJson().get("thrift-service").getAddress());
helloClient.setPort(getAllConsulService.allServiceJson().get("thrift-service").getPort());
return helloClient;
}
}
verification
Write a controller Let's try :
@RestController
@RequestMapping("/")
@Slf4j
public class HelloController {
@Autowired
private HelloClient helloClient;
@GetMapping
public String getHello(String name){
try {
helloClient.open();
return helloClient.getHelloService().sayHello(name);
}catch (Exception e){
log.error("error: ", e.getMessage());
}finally {
helloClient.close();
}
return "";
}
}
summary
This paper implements a minimalist version of consul+springcloud+thrift Application , But there are still many places that can be optimized , Including the security of registration , Security check strategy of service , Service startup logic , Service acquisition logic ,prometheus Join monitoring , Load balancing , use netty Replace the default communication protocol, etc , You can explore , You can also wait until I want to do it one day ~
Welcome to contact :[email protected]
边栏推荐
- J9 number theory: what factors determine the value of NFT?
- Basic label in body
- AlphaFold揭示了蛋白质结构宇宙-从近100万个结构扩展到超过2亿个结构
- 全面升级,你能想象的都在这————京东API接口
- The brutal rule of blackmail software continues, and attacks increase by 105%
- New 1688 API access instructions
- golang run时报undefined错误【已解决】
- Comprehensive upgrade, all you can imagine is here -- JD API interface
- C language 300 lines of code to achieve mine sweeping (deployable + markable + changeable difficulty level)
- MySQL execution order
猜你喜欢

【HCIP】重发布及路由策略的实验

560 and K

Embedded sharing collection 23

T-sne降维
![[SQL's 18 dragon subduing palms] 01 - Kang long regrets: introductory 10 questions](/img/db/d0255d7036f7003d380c8888fed88b.png)
[SQL's 18 dragon subduing palms] 01 - Kang long regrets: introductory 10 questions

TDA75610-I2C-模拟功放I2C地址的确定

Use of resttemplate and Eureka

Basic label in body

560 和为 K 的子数组
![[observation] ranked first in SaaS of pure public cloud in three years, and yonsuite's](/img/d8/a367c26b51d9dbaf53bf4fe2a13917.png)
[observation] ranked first in SaaS of pure public cloud in three years, and yonsuite's "flywheel effect"
随机推荐
围绕新市民金融聚焦差异化产品设计、智能技术提效及素养教育
TypeError: can only concatenate str (not “int“) to str
10 major network security incidents in the past 10 years
BOM系列之定时器
After understanding the composition of the URL of the website, we use the URL module, querystring module and mime module to improve the static website
Plato launched the LAAS protocol elephant swap, which allows users to earn premium income
PCL 点云转强度图像
Openpyxl border
什么是原码、反码和补码
Plato launched the LAAS protocol elephant swap, which allows users to earn premium income
Test / development programmers rely on technology to survive the midlife crisis? Improve your own value
明日无限计划,2022某公司元宇宙产品发布会活动概念策划方案
uniapp createSelectorQuery(). Select get returns null error
云原生应用综合练习下
The solution to keep the height of the container unchanged during the scaling process of the uniapp movable view table
C language 300 lines of code to achieve mine sweeping (deployable + markable + changeable difficulty level)
活动速递| Apache Doris 性能优化实战系列直播课程初公开,诚邀您来参加!
What are source code, inverse code and complement code
What are the common cyber threats faced by manufacturers and how do they protect themselves
TDA75610-I2C-模拟功放I2C地址的确定