微服务项目整合遇到的一些问题

Posted by zhida on May 2, 2016

将遇到的一些问题记录在这里,方便后面遇到相同问题的同学,能够有一些思路上的帮助

接口返回 xml格式

这个依赖引入了 xml 的包,所以自动转成了xml格式

<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-eureka-server</artifactId>
	<exclusions>
		<exclusion>
			<groupId>com.fasterxml.jackson.dataformat</groupId>
			<artifactId>jackson-dataformat-xml</artifactId>
		</exclusion>
	</exclusions>
</dependency>

一直报错register with the peer,但是不影响使用

DiscoveryClient_UNKNOWN/bogon - de-registration failedCannot execute request on any known server

By default every Eureka server is also a Eureka client and requires (at least one) service URL to locate a peer. If you don’t provide it the service will run and work, but it will shower your logs with a lot of noise about not being able to register with the peer.

解决Docker容器,在Eureka注册的IP地址为内网IP192.168.0.X的问题

Need to tell eureka client running in Docker to use host’s IP Force the name / ipaddress with which Eureka client registers at the server Microservices registering Docker internal IP on Eureka instead of public one

  • 微服务配置:
eureka:
  instance:
    instance-id: ${spring.cloud.client.ipAddress}:${server.port}:${spring.application.name}
    preferIpAddress: true	  	# 关键
    hostname: 10.170.48.177 	# 关键
    ipAddress: 10.170.48.177 	# 关键   可以在docker-compose配置	

  • 服务的IP设置为 0.0.0.0

  • 用于帮助调试的测试代码

@RestController
@RequestMapping("/test")
public class TestResource {

	private static final Logger logger = LoggerFactory.getLogger(TestResource.class);

	@Autowired
	private DiscoveryClient discoveryClient;

	@Autowired
	private BookmarkClient bookmarkClient;

	@RequestMapping(value = "/a", method = RequestMethod.GET)
	public void test() {

		logger.debug(" discoveryClient-- >" + discoveryClient + "<--");

		ServiceInstance local = discoveryClient.getLocalServiceInstance();
		logger.debug("local--:" + ToStringBuilder.reflectionToString(local) + "--" + local.getHost() + "~"
				+ local.getUri() + "~" + local.getServiceId());

		List<String> services = discoveryClient.getServices();
		for (String str : services) {
			logger.debug(str + "   ~~~service~~~");
		}

		List<ServiceInstance> lists = discoveryClient.getInstances("ticket-service");

		logger.debug(lists.size() + ":lists.size");

		for (ServiceInstance serviceInstance : lists) {
			logger.debug("serviceInstance--:" + serviceInstance.getHost() + "~" + serviceInstance.getUri() + "~"
					+ serviceInstance.getServiceId());
		}

		try {
			Message<Object> msg = bookmarkClient.getBookmarks("1");
			logger.debug(msg.toString() + "~~~~~");
		} catch (Exception e) {
			logger.debug("~~~~2~");
			e.printStackTrace();
		}

	}
}
  • 其他方案,修改默认的配置

    • 覆盖 EurekaInstanceConfigBean
    • Something that can be done from docker is just using the docker run -h hostname or ip Eureka will pick up the host name since it it written to the etc/hosts file

TimedSupervisorTask - task supervisor threw an exception java.lang.OutOfMemoryError: PermGen space

16:25:15.874 192.168.0.10 [DiscoveryClient-HeartbeatExecutor-5] ERROR c.netflix.discovery.DiscoveryClient - DiscoveryClient_YEA-MSG/192.168.0.10:8083:yea-msg - was unable to send heartbeat!
java.lang.OutOfMemoryError: PermGen space
16:26:27.909 192.168.0.10 [DiscoveryClient-2] ERROR c.n.discovery.TimedSupervisorTask - task supervisor timed out
java.util.concurrent.TimeoutException: null
	at java.util.concurrent.FutureTask.get(FutureTask.java:201)
	at com.netflix.discovery.TimedSupervisorTask.run(TimedSupervisorTask.java:64)
	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
	at java.util.concurrent.FutureTask.run(FutureTask.java:262)
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:178)
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:292)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)

1、参考这篇文章 [转]spring cloud eureka 参数配置.md 修改参数:leaseRenewalIntervalInSeconds leaseExpirationDurationInSeconds

2、修改日志等级(不可取)

logging:
  level:
    com.netflix.discovery.TimedSupervisorTask: "OFF"

3、修改以下配置

eureka.instance.hostname=localhost
eureka.instance.port=8761

spring.application.name=eureka
spring.cloud.config.enabled=false

server.port=${eureka.instance.port}

eureka.server.enableSelfPreservation=false

eureka.client.registerWithEureka=false
eureka.client.fetchRegistry=false
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${eureka.instance.port}/eureka/
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-parent</artifactId>
        **<version>Camden.SR4</version>**
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>
 
   <dependencies>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-eureka-server</artifactId>
    </dependency>
  </dependencies>

spring.cloud.config.enabled=true
spring.application.name=<name>
#Uncomment service discovery or URI
spring.cloud.config.discovery.enabled=true
spring.cloud.config.uri=<URI>
Spring Boot version: 1.4.0
Spring Cloud Netflix: Camdem.SR4
Spring Cloud Config: 1.2.3.RELEASE (**the error only reproduces with Spring Cloud Config**. If I use local configuration, the error doesn't show)

Upgrade the Netflix version, shows the log in warn level, is that the solution for this problem?

4、修改版本

I just updated the sample proyect to work with Spring Boot 1.5.4.RELEASE and Spring Cloud Dalston.SR1. With this setup the exception no longer shows up. Thank you for having a look at it.

5、Hi @codependent , with Spring Boot 1.5.4.RELEASE the exception dissapear, thanks.

https://github.com/spring-cloud/spring-cloud-netflix/issues/1055

TimeoutException

13:38:14.531 [hystrix-ticket-service-1] DEBUG cn.yeamoney.console.ipc.TicketClient - [TicketClient#getList] ---> GET http://ticket-service/list/console?amountA=0&amountB=99999999&createTimeA=1970-01-01&createTimeB=2100-01-01&expireTimeA=1970-01-01&expireTimeB=2100-01-01&pageIndex=1&pageSize=10&orderFiled=&orderType= HTTP/1.1
13:38:14.533 [hystrix-ticket-service-1] DEBUG cn.yeamoney.console.ipc.TicketClient - [TicketClient#getList] ---> END HTTP (0-byte body)
13:38:14.576 [hystrix-ticket-service-1] INFO  o.s.c.a.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@1f8f657d: startup date [Thu Jun 29 13:38:14 CST 2017]; parent: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@33728d1e
13:38:14.711 [hystrix-ticket-service-1] INFO  o.s.b.f.a.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
13:38:15.132 [hystrix-ticket-service-1] INFO  c.n.config.ChainedDynamicProperty - Flipping property: ticket-service.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
13:38:15.157 [hystrix-ticket-service-1] INFO  c.n.u.c.ShutdownEnabledTimer - Shutdown hook installed for: NFLoadBalancer-PingTimer-ticket-service
13:38:15.186 [hystrix-ticket-service-1] INFO  c.n.loadbalancer.BaseLoadBalancer - Client:ticket-service instantiated a LoadBalancer:DynamicServerListLoadBalancer:{NFLoadBalancer:name=ticket-service,current list of Servers=[],Load balancer stats=Zone stats: {},Server stats: []}ServerList:null
13:38:15.190 [hystrix-ticket-service-1] INFO  c.n.l.DynamicServerListLoadBalancer - Using serverListUpdater PollingServerListUpdater
13:38:15.215 [hystrix-ticket-service-1] INFO  c.n.config.ChainedDynamicProperty - Flipping property: ticket-service.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
13:38:15.217 [hystrix-ticket-service-1] INFO  c.n.l.DynamicServerListLoadBalancer - DynamicServerListLoadBalancer for client ticket-service initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=ticket-service,current list of Servers=[192.168.0.7:1000],Load balancer stats=Zone stats: {defaultzone=[Zone:defaultzone;	Instance count:1;	Active connections count: 0;	Circuit breaker tripped count: 0;	Active connections per server: 0.0;]
},Server stats: [[Server:192.168.0.7:1000;	Zone:defaultZone;	Total Requests:0;	Successive connection failure:0;	Total blackout seconds:0;	Last connection made:Thu Jan 01 08:00:00 CST 1970;	First connection made: Thu Jan 01 08:00:00 CST 1970;	Active Connections:0;	total failure count in last (1000) msecs:0;	average resp time:0.0;	90 percentile resp time:0.0;	95 percentile resp time:0.0;	min resp time:0.0;	max resp time:0.0;	stddev resp time:0.0]

Ansewer:

hystrix:
  command:
    default:
      execution:
        timeout:
          enabled: false
      circuitBreaker:
        enabled: true
        requestVolumeThreshold: 3

SocketTimeoutException

16:56:21.212 [hystrix-ticket-service-1] DEBUG cn.yeamoney.console.ipc.TicketClient - [TicketClient#getList] ---> GET http://ticket-service/list/console?amountA=0&amountB=99999999&createTimeA=1970-01-01&createTimeB=2100-01-01&expireTimeA=1970-01-01&expireTimeB=2100-01-01 HTTP/1.1
16:56:21.212 [hystrix-ticket-service-1] DEBUG cn.yeamoney.console.ipc.TicketClient - [TicketClient#getList] ---> END HTTP (0-byte body)
16:56:21.252 [hystrix-ticket-service-1] INFO  o.s.c.a.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@6c016514: startup date [Thu Jun 29 16:56:21 CST 2017]; parent: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@7ba9a15f
16:56:21.306 [hystrix-ticket-service-1] INFO  o.s.b.f.a.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
16:56:21.537 [hystrix-ticket-service-1] INFO  c.n.config.ChainedDynamicProperty - Flipping property: ticket-service.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
16:56:21.560 [hystrix-ticket-service-1] INFO  c.n.u.c.ShutdownEnabledTimer - Shutdown hook installed for: NFLoadBalancer-PingTimer-ticket-service
16:56:21.589 [hystrix-ticket-service-1] INFO  c.n.loadbalancer.BaseLoadBalancer - Client:ticket-service instantiated a LoadBalancer:DynamicServerListLoadBalancer:{NFLoadBalancer:name=ticket-service,current list of Servers=[],Load balancer stats=Zone stats: {},Server stats: []}ServerList:null
16:56:21.595 [hystrix-ticket-service-1] INFO  c.n.l.DynamicServerListLoadBalancer - Using serverListUpdater PollingServerListUpdater
16:56:21.621 [hystrix-ticket-service-1] INFO  c.n.config.ChainedDynamicProperty - Flipping property: ticket-service.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
16:56:21.625 [hystrix-ticket-service-1] INFO  c.n.l.DynamicServerListLoadBalancer - DynamicServerListLoadBalancer for client ticket-service initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=ticket-service,current list of Servers=[192.168.0.7:1000],Load balancer stats=Zone stats: {defaultzone=[Zone:defaultzone;	Instance count:1;	Active connections count: 0;	Circuit breaker tripped count: 0;	Active connections per server: 0.0;]
},Server stats: [[Server:192.168.0.7:1000;	Zone:defaultZone;	Total Requests:0;	Successive connection failure:0;	Total blackout seconds:0;	Last connection made:Thu Jan 01 08:00:00 CST 1970;	First connection made: Thu Jan 01 08:00:00 CST 1970;	Active Connections:0;	total failure count in last (1000) msecs:0;	average resp time:0.0;	90 percentile resp time:0.0;	95 percentile resp time:0.0;	min resp time:0.0;	max resp time:0.0;	stddev resp time:0.0]
]}ServerList:org.springframework.cloud.netflix.ribbon.eureka.DomainExtractingServerList@3015ab52
16:56:22.600 [PollingServerListUpdater-0] INFO  c.n.config.ChainedDynamicProperty - Flipping property: ticket-service.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
16:56:26.737 [hystrix-ticket-service-1] DEBUG cn.yeamoney.console.ipc.TicketClient - [TicketClient#getList] <--- ERROR SocketTimeoutException: connect timed out (5524ms)
16:56:26.739 [hystrix-ticket-service-1] DEBUG cn.yeamoney.console.ipc.TicketClient - [TicketClient#getList] java.net.SocketTimeoutException: connect timed out

hystrix:
  command:
    default:
      execution:
        timeout:
          enabled: false
        isolation:
          thread:
            timeoutInMilliseconds: 5000
      circuitBreaker:
        enabled: true
        requestVolumeThreshold: 3