beancloud礦池
㈠ springcloud 能做rpc調用么
在 spring cloud 的老版本中(比如 Angel.SR3), 是自動添加了RestTemplate這個Bean,只要在相應的類中自動裝配 RestTemplate 這個 Bean:
@Autowired
RestTemplate restTemplate;1212
就可以直接使用getForObject方法進行RPC:
restTemplate.getForObject(String url, Class<String> responseType, Object... uriVariables))11
2,而在比較新的版本中(比如 Camden.SR7), 是沒有自動添加RestTemplate這個Bean的,需要手動添加(大坑1);並且還需要加上註解@LoadBalanced(超級大坑2,這里說超級大坑是因為沒有資料提到這個註解, 在這里糾結了很久,解決的時候還是很開心的呢);
@LoadBalanced
@Bean
public RestTemplate rest() {
return new RestTemplate();
}
㈡ spring 中怎麼取得bean
總共有6種方法可以實現:
方法一:在初始化時保存ApplicationContext對象
方法二:通過Spring提供的utils類獲取ApplicationContext對象
方法三:繼承自抽象類ApplicationObjectSupport
方法四:繼承自抽象類WebApplicationObjectSupport
方法五:通過Spring提供的ContextLoader
獲取spring中bean的方式總結:
方法一:在初始化時保存ApplicationContext對象
ApplicationContext ac = new ("applicationContext.xml"); ac.getBean("userService");//比如:<bean id="userService" class="com.cloud.service.impl.UserServiceImpl"></bean>
說明:這樣的方式適用於採用Spring框架的獨立應用程序,須要程序通過配置文件手工初始化Spring的情況。
方法二:通過Spring提供的工具類獲取ApplicationContext對象
ApplicationContext ac1 = WebApplicationContextUtils.(ServletContext sc); ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc); ac1.getBean("beanId"); ac2.getBean("beanId");
說明:這樣的方式適合於採用Spring框架的B/S系統,通過ServletContext對象獲取ApplicationContext對象。然後在通過它獲取須要的類實例。上面兩個工具方式的差別是,前者在獲取失敗時拋出異常。後者返回null。
方法三:繼承自抽象類ApplicationObjectSupport
說明:抽象類ApplicationObjectSupport提供getApplicationContext()方法。能夠方便的獲取ApplicationContext。
Spring初始化時。會通過該抽象類的setApplicationContext(ApplicationContext context)方法將ApplicationContext 對象注入。
方法四:繼承自抽象類WebApplicationObjectSupport
說明:類似上面方法。調用getWebApplicationContext()獲取WebApplicationContext
方法五:通過Spring提供的ContextLoader
WebApplicationContext wac = ContextLoader.();wac.getBean(beanID);
㈢ springcloud 能做rpc調用么
://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<bean id=""
class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean">
<property name="serviceUrl" value="${userpoints.api.serviceUrl}" />
<property name="serviceInterface"
value="${userpoints.api.interface.service}" />
<property name="httpInvokerRequestExecutor">
<ref bean="httpInvokerRequestExecutor" />
</property>