锘??xml version="1.0" encoding="utf-8" standalone="yes"?> java -javaagent:E:\repository\org\springframework\spring-load\springloaded-1.2.5.RELEASE.jar -noverify -Dspringloaded=watchJars=main.jar main.jar 鏀瑰彉涓?/p>
boolean result = false;
// try(MongoCursor<String> mongoCursor =
// mongoTemplate.getCollection(mongoTemplate.getCollectionName(AccountNumProductLineIndex.class))
// .distinct(KEY, Filters.eq(REQUEST_ID, requestId), String.class)
// .iterator()
// )
try(MongoCursor<Document> mongoCursor =
mongoTemplate.getCollection(mongoTemplate.getCollectionName(AccountNumProductLineIndex.class))
.aggregate(
Arrays.asList(
Aggregates.project(
Projections.fields(
Projections.excludeId(),
Projections.include(KEY),
Projections.include(REQUEST_ID)
)
),
Aggregates.match(Filters.eq(REQUEST_ID, requestId)),
Aggregates.group("$" + KEY)
)
)
.allowDiskUse(true)
.iterator();
)
{
String key = null;
boolean breakMe = false;
LOGGER.info("needReorderCheck.key --> start");
while(mongoCursor.hasNext()) {
if(breakMe) {
mongoCursor.close();
break;
}
Document keyDocument = mongoCursor.next();
key = keyDocument.getString("_id");
// key = mongoCursor.next().getString(KEY);
// LOGGER.info("needReorderCheck.keyDocument --> {}, key --> {}", keyDocument, key);
try(MongoCursor<Document> indexMongoCursor =
mongoTemplate.getCollection(AccountNumProductLineIndex.COLLECTION_NAME)
.find(Filters.and(Filters.eq(REQUEST_ID, requestId), Filters.eq(KEY, key)))
.iterator()
)
{
int preIndex = -1, currentIndex = -1;
Document preIndexDocument = null, currentIndexDocument;
while(indexMongoCursor.hasNext()) {
currentIndexDocument = indexMongoCursor.next();
// System.out.println(currentIndexDocument.toJson());
if(preIndexDocument != null) {
currentIndex = currentIndexDocument.getInteger(INDEX);
preIndex = preIndexDocument.getInteger(INDEX);
if(currentIndex - preIndex > 1) {
indexMongoCursor.close();
breakMe = true;
result = true;
break;
}
}
preIndexDocument = currentIndexDocument;
}
}
}
}
return result;
}
]]>
https://github.com/amitrp/spring-examples/blob/main/spring-webflux-webclient/src/main/java/com/amitph/spring/webclients/service/FileDownloaderWebClientService.java
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Objects;
@Service
@RequiredArgsConstructor
public class FileDownloaderWebClientService {
private final WebClient webClient;
/**
* Reads the complete file in-memory. Thus, only useful for very large file
*/
public void downloadUsingByteArray(Path destination) throws IOException {
Mono<byte[]> monoContents = webClient
.get()
.uri("/largefiles/1")
.retrieve()
.bodyToMono(byte[].class);
Files.write(destination, Objects.requireNonNull(monoContents.share().block()),
StandardOpenOption.CREATE);
}
/**
* Reading file using Mono will try to fit the entire file into the DataBuffer.
* Results in exception when the file is larger than the DataBuffer capacity.
*/
public void downloadUsingMono(Path destination) {
Mono<DataBuffer> dataBuffer = webClient
.get()
.uri("/largefiles/1")
.retrieve()
.bodyToMono(DataBuffer.class);
DataBufferUtils.write(dataBuffer, destination,
StandardOpenOption.CREATE)
.share().block();
}
/**
* Having using Flux we can download files of any size safely.
* Optionally, we can configure DataBuffer capacity for better memory utilization.
*/
public void downloadUsingFlux(Path destination) {
Flux<DataBuffer> dataBuffer = webClient
.get()
.uri("/largefiles/1")
.retrieve()
.bodyToFlux(DataBuffer.class);
DataBufferUtils.write(dataBuffer, destination,
StandardOpenOption.CREATE)
.share().block();
}
}
]]>
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.IntegrationFlows;
import org.springframework.integration.dsl.Transformers;
import org.springframework.integration.http.dsl.Http;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class SpringIntegrationEnricherApplication {
public static void main(String[] args) {
SpringApplication.run(SpringIntegrationEnricherApplication.class, args);
}
@Bean
public IntegrationFlow jsonEnricherFlow(RestTemplate restTemplate) {
return IntegrationFlows.from(Function.class)
.transform(Transformers.fromJson(Map.class))
.enrich((enricher) -> enricher
.<Map<String, ?>>requestPayload((message) ->
((List<?>) message.getPayload().get("attributeIds"))
.stream()
.map(Object::toString)
.collect(Collectors.joining(",")))
.requestSubFlow((subFlow) ->
subFlow.handle(
Http.outboundGateway("/attributes?id={ids}", restTemplate)
.httpMethod(HttpMethod.GET)
.expectedResponseType(Map.class)
.uriVariable("ids", "payload")))
.propertyExpression("attributes", "payload.attributes"))
.<Map<String, ?>, Map<String, ?>>transform(
(payload) -> {
payload.remove("attributeIds");
return payload;
})
.transform(Transformers.toJson())
.get();
}
}
https://stackoverflow.com/questions/58205432/spring-integration-enrich-transform-message-using-rest-call
https://www.tabnine.com/web/assistant/code/rs/5c781b6ae70f87000197ab9f#L312
]]>
import org.springframework.context.ApplicationEvent;
@Getter
public class JavaStackEvent extends ApplicationEvent {
/**
* Create a new {@code ApplicationEvent}.
*
* @param source the object on which the event initially occurred or with
* which the event is associated (never {@code null})
*/
public JavaStackEvent(Object source) {
super(source);
}
}
瀹氫箟涓涓浜嬩歡瑙傚療鑰咃紝鍗蟲劅鍏磋叮鑰咃細
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
/**
* 瑙傚療鑰咃細璇昏呯矇涓?br /> */
@RequiredArgsConstructor
public class ReaderListener implements ApplicationListener<JavaStackEvent> {
@NonNull
private String name;
private String article;
@Async
@Override
public void onApplicationEvent(JavaStackEvent event) {
// 鏇存柊鏂囩珷
updateArticle(event);
}
private void updateArticle(JavaStackEvent event) {
this.article = (String) event.getSource();
System.out.printf("鎴戞槸璇昏咃細%s錛屾枃绔犲凡鏇存柊涓猴細%s\n", this.name, this.article);
}
}
娉ㄥ唽鎰熷叴瓚h咃紙灝嗚嚜韜敞鍏PRING瀹瑰櫒鍒欏畬鎴愭敞鍐岋級錛屽茍鍒跺畾鍙戝竷鏈哄埗錛堥氳繃CONTEXT鍙戝竷浜嬩歡錛夛細
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Slf4j
@Configuration
public class ObserverConfiguration {
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext context) {
return (args) -> {
log.info("鍙戝竷浜嬩歡錛氫粈涔堟槸瑙傚療鑰呮ā寮忥紵");
context.publishEvent(new JavaStackEvent("浠涔堟槸瑙傚療鑰呮ā寮忥紵"));
};
}
@Bean
public ReaderListener readerListener1(){
return new ReaderListener("灝忔槑");
}
@Bean
public ReaderListener readerListener2(){
return new ReaderListener("灝忓紶");
}
@Bean
public ReaderListener readerListener3(){
return new ReaderListener("灝忕埍");
}
}
]]>
鎺屾彙浜嗚繖鐐圭浉淇′貢鐮佸凡緇忔棤娉曢樆鎸℃垜浠墠榪涚殑姝ヤ紣浜嗭細鍙渶灝嗕笉甯?bom 澶寸紪鐮佺殑 csv 鏂囦歡錛岀敤鏂囨湰緙栬緫鍣紙宸ュ叿闅忔剰錛屾帹鑽?notepad++ 錛夋墦寮騫惰漿鎹負甯?bom 鐨勭紪鐮佸艦寮忥紙鍏蜂綋緙栫爜鏂瑰紡闅忔剰錛夛紝闂瑙e喅銆?br />
褰撶劧錛屽鏋滀綘鏄儚鎴戜竴鏍風殑鐮佸啘鍝ュ摜錛屽湪鐢熸垚 csv 鏂囦歡鐨勬椂鍊欏啓鍏?bom 澶存洿鐩存帴鐐癸紝鐢ㄦ埛浼氭劅璋綘鐨勩?br />
闄勫綍錛氬浜?utf-8 緙栫爜錛寀nicode 鏍囧噯涓槸娌℃湁 bom 瀹氫箟鐨勶紝寰蔣鍦ㄨ嚜宸辯殑 utf-8 鏍煎紡鐨勬枃鏈枃浠朵箣鍓嶅姞涓婁簡EF BB BF涓変釜瀛楄妭浣滀負璇嗗埆姝ょ紪鐮佺殑 bom 澶達紝榪欎篃瑙i噴浜嗕負鍟ュぇ閮ㄥ垎涔辯爜閮芥槸 utf-8 緙栫爜瀵艱嚧鐨勫師鍥?br />
SPRING BATCH涓敓鎴怌SV鏂囦歡鏃剁殑瑙e喅鏂規錛?br />
.name(itemWriterName)
.resource(outputResource)
.lineAggregator(lineAggregator)
.headerCallback(
h -> {
System.out.println(header);
h.write('\uFEFF');//鍙渶鍔犺繖涓琛?/span>
h.write(header);
}
)
.build();
https://stackoverflow.com/questions/48952319/send-csv-file-encoded-in-utf-8-with-bom-in-java
]]>
private LocalDate getValidExpireDate() {
try {
return LocalDate.parse(this.dateString, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
} catch (Exception e) {
return null;
}
}
姝ゆ柟娉曞dateString榪涜瑙i噴錛岃繑鍥濴ocalDate錛屽鏋渄ateString涓虹┖鎴栨牸寮忛敊璇紝鍒欒繑鍥炵┖錛屽啀閰嶅悎@Future 榪涜鏄惁鏈潵鏃ユ湡鐨勯獙璇併?br />
]]>
private Boolean getValidImg() {
if(YNEnum.Y.code.equals(super.getNeedChecked())) {
return StringUtils.hasText(this.img);
}
return null;//igore checking.
}
榪欎釜鏄綋needChecked涓篩鐨勬椂鍊欐墠鎵ц媯鏌mg鍙橀噺鏄惁涓虹┖銆?br />鏈夊嚑鐐規敞鎰忥細
]]>
鍙鍦↗AVA BEAN涓渶瑕侀獙璇佺殑瀛楁鍔燖NotNull榪欑鏍囩錛岀劧鍚庡湪SERVISE涓殑杈撳叆鍙傛暟涓姞@Valid鏍囩錛屽垯灝辨縺媧婚獙璇佹祦紼嬨?br />涔熷彲浠ョ紪紼嬬殑鏂瑰紡鑷繁楠岃瘉錛?br />
//@Validated
public class MqMessageCcdValidator {
private static final Logger LOGGER = LoggerFactory.getLogger(MqMessageCcdValidator.class);
@Autowired
private Validator validator;
@ServiceActivator
public MqMessage<CcdRequest> validate(/* @Valid */ Message<MqMessage<CcdRequest>> requestMessage) {
Set<ConstraintViolation<MqMessage<CcdRequest>>> set = validator.validate(requestMessage.getPayload());
if(CollectionUtils.isNotEmpty(set)) {
CompositeException compositeException = new CompositeException();
set.forEach(
constraintViolation -> {
LOGGER.info("{}", constraintViolation);
ReqInfoValidationException exception =
new ReqInfoValidationException(constraintViolation.getMessage());
compositeException.addException(exception);
}
);
throw new MessageHandlingException(requestMessage, compositeException);
}
return requestMessage.getPayload();
}
}
鑷畾涔夐獙璇佽鍒?br />鍙敤鏍囩鏉ュ仛錛屼互涓嬩負楠岃瘉鎵嬫満鍙風殑瑙勫垯錛?br />
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
import javax.validation.ReportAsSingleViolation;
import javax.validation.constraints.Pattern;
@Retention(RUNTIME)
@Target(value = { ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE })
@Constraint(validatedBy = {})
@ReportAsSingleViolation
@Pattern(regexp = "^1[3-9]\\d{9}$")
public @interface ChinaPhone {
String message() default "Invalid Chinese mobile No.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
濡傛灉姣旇緝澶嶆潅鐨勯獙璇佽鍒欙紝鍒欏弬瑙侊細
https://reflectoring.io/bean-validation-with-spring-boot/#implementing-a-custom-validator
How to use Java Bean Validation in Spring Boot
https://nullbeans.com/how-to-use-java-bean-validation-in-spring-boot/
Complete Guide to Validation With Spring Boot
https://reflectoring.io/bean-validation-with-spring-boot/
Spring JMS Validate Messages using JSR-303 Bean Validation
https://memorynotfound.com/spring-jms-validate-messages-jsr-303-bean-validation/
Spring REST Validation Example
https://mkyong.com/spring-boot/spring-rest-validation-example/
Spring Boot 鏁村悎 Bean Validation 鏍¢獙鏁版嵁
https://blog.csdn.net/wangzhihao1994/article/details/108403732
]]>
https://stackoverflow.com/questions/50608415/cwsia0112e-the-property-name-keep-alive-is-not-a-valid-java-identifier
]]>
RestTemplate鎻愪緵浜嗗縐嶄究鎹瘋闂繙紼婬ttp鏈嶅姟鐨勬柟娉?鑳藉澶уぇ鎻愰珮瀹㈡埛绔殑緙栧啓鏁堢巼銆?br />
璋冪敤RestTemplate鐨勯粯璁ゆ瀯閫犲嚱鏁幫紝RestTemplate瀵硅薄鍦ㄥ簳灞傞氳繃浣跨敤java.net鍖呬笅鐨勫疄鐜板垱寤篐TTP 璇鋒眰錛?br />
鍙互閫氳繃浣跨敤ClientHttpRequestFactory鎸囧畾涓嶅悓鐨凥TTP璇鋒眰鏂瑰紡銆?br />
ClientHttpRequestFactory鎺ュ彛涓昏鎻愪緵浜嗕袱縐嶅疄鐜版柟寮?br />
1銆佷竴縐嶆槸SimpleClientHttpRequestFactory錛屼嬌鐢↗2SE鎻愪緵鐨勬柟寮忥紙鏃ava.net鍖呮彁渚涚殑鏂瑰紡錛夊垱寤哄簳灞傜殑Http璇鋒眰榪炴帴銆?br />
2銆佷竴縐嶆柟寮忔槸浣跨敤HttpComponentsClientHttpRequestFactory鏂瑰紡錛屽簳灞備嬌鐢℉ttpClient璁塊棶榪滅▼鐨凥ttp鏈嶅姟錛屼嬌鐢℉ttpClient鍙互閰嶇疆榪炴帴姹犲拰璇佷功絳変俊鎭?br />
榛樿鐨?RestTemplate 鏈変釜鏈哄埗鏄姹傜姸鎬佺爜闈?00 灝辨姏鍑哄紓甯革紝浼氫腑鏂帴涓嬫潵鐨勬搷浣溿傚鏋滀笉鎯充腑鏂緇撴灉鏁版嵁寰楄В鏋愶紝鍙互閫氳繃瑕嗙洊榛樿鐨?ResponseErrorHandler 錛岃涓嬮潰鐨勭ず渚嬶紝紺轟緥涓殑鏂規硶涓熀鏈兘鏄┖鏂規硶錛屽彧瑕佸hasError淇敼涓嬶紝璁╀粬涓鐩磋繑鍥瀟rue錛屽嵆鏄笉媯鏌ョ姸鎬佺爜鍙婃姏寮傚父浜嗐?br />
import java.io.IOException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) throws Exception {
RestTemplate restTemplate = new RestTemplate(factory);
ResponseErrorHandler responseErrorHandler = new ResponseErrorHandler() {
@Override
public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
return true;
}
@Override
public void handleError(ClientHttpResponse clientHttpResponse) throws IOException {
}
};
restTemplate.setErrorHandler(responseErrorHandler);
return restTemplate;
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
//璇誨彇瓚呮椂5縐?/span>
factory.setReadTimeout(5000);
//榪炴帴瓚呮椂15縐?/span>
factory.setConnectTimeout(15000);
return factory;
}
}
RestTemppate榪愮敤瀹炰緥
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.example.demo.domain.Book;
@RestController
public class TestBookController {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private RestTemplate restTemplate;
@GetMapping("/testaddbook")
public Book testAddBook() {
Book book = new Book();
ResponseEntity<Book> responseEntity = restTemplate.postForEntity( "http://localhost:8061/book", book , Book.class);
return responseEntity.getBody();
}
}
鍏朵粬鏂規硶錛宑atch HttpStatusCodeException , e.getResponseBodyAsString()
ResponseEntity<Component> response = restTemplate.exchange(webSvcURL,
HttpMethod.POST,
requestEntity,
Component.class);
} catch (HttpStatusCodeException e) {
List<String> customHeader = e.getResponseHeaders().get("x-app-err-id");
String svcErrorMessageID = "";
if (customHeader != null) {
svcErrorMessageID = customHeader.get(0);
}
throw new CustomException(e.getMessage(), e, svcErrorMessageID);
// You can get the body too but you will have to deserialize it yourself
// e.getResponseBodyAsByteArray()
// e.getResponseBodyAsString()
}
https://stackoverflow.com/questions/7878002/resttemplate-handling-response-headers-body-in-exceptions-restclientexception
https://stackoverflow.com/questions/38093388/spring-resttemplate-exception-handling/51805956#51805956
]]>
public IntegrationFlow provisionUserFlow() {
return
IntegrationFlows.from("input.channel")
.publishSubscribeChannel(Executors.newCachedThreadPool(),
s -> s.applySequence(true)
.subscribe(f -> f.enrichHeaders(e -> e.header(MessageHeaders.ERROR_CHANNEL, "errorChannel", true))
.handle(provisionerA, "provision")
.channel("aggregatorChannel")
)
.subscribe(f -> f.enrichHeaders(e -> e.header(MessageHeaders.ERROR_CHANNEL, "errorChannel", true))
.handle(provisionerB, "provision")
.channel("aggregatorChannel"))
)
.get();
}
@Bean
public IntegrationFlow aggregateFlow() {
return IntegrationFlows.from("aggregatorChannel")
.channel( aggregatorChannel)
.aggregate( a -> a.processor( collect, "aggregatingMethod"))
.get();
}
@Transformer( inputChannel = "errorChannel", outputChannel = "aggregatorChannel")
public Message<?> errorChannelHandler(ErrorMessage errorMessage) throws RuntimeException {
Message<?> failedMessage = ((MessagingException) errorMessage.getPayload()).getFailedMessage();
Exception exception = (Exception) errorMessage.getPayload();
return MessageBuilder.withPayload( exception.getMessage())
.copyHeadersIfAbsent( failedMessage.getHeaders() )
.build();
}
https://stackoverflow.com/q/46495127/11790720
]]>
public IntegrationFlow parallelSplitRouteAggregateFlow() {
return IntegrationFlows
.from(Http.inboundGateway("/trigger"))
.handle((p, h) -> Arrays.asList(1, 2, 3))
.split()
.channel(MessageChannels.executor(Executors.newCachedThreadPool()))
.<Integer, Boolean>route(o -> o % 2 == 0, m -> m
.subFlowMapping(true, sf -> sf.gateway(oddFlow()))
.subFlowMapping(false, sf -> sf.gateway(evenFlow())))
.aggregate()
.get();
}
@Bean
public IntegrationFlow oddFlow() {
return flow -> flow.<Integer>handle((payload, headers) -> "odd");
}
@Bean
public IntegrationFlow evenFlow() {
return flow -> flow.<Integer>handle((payload, headers) -> "even");
}
https://stackoverflow.com/questions/50121384/spring-integration-parallel-split-route-aggregate-flow-fails-due-to-one-way-mess
]]>
]]>
]]>
鍏朵腑appender鏄敤鏉ヨ緭鍑烘棩蹇楋紝鏈塮ile鍜宑onsole涓や釜瀹炵幇錛宑onsole鍒欐槸鍚戞帶鍒跺彴杈撳嚭鏃ュ織錛岃宖ile鍒欐槸鍚戞枃浠惰緭鍑烘棩蹇椼?br />rolling file appender涓紝鏈塺ollingPolicy鍜宼riggerPolicy涓や釜涓昏灞炴э紝rollingPolicy鏄‘瀹氬浣曞鐞嗘棩蹇楁枃浠訛紝鑰宼riggerPolicy鍒欐槸紜畾浣曟椂澶勭悊鏃ュ織鏂囦歡銆?br />
濡傛灉瑕佷嬌鐢⊿PRING閽堝LOGBACK鐨勪竴浜涘姛鑳斤紝濡俻rofile絳夛紝鍒欒灝唋ogback.xml鐨勯厤緗枃浠跺懡鍚嶄負logback-spring.xml錛屽茍鍦⊿PRING涓厤緗紝logging.config= logback-spring.xml銆?br />
SPRING浼氬皢logging.file銆乴ogging.path榪欎簺閰嶇疆杞垚緋葷粺鍙橀噺LOG_FILE銆丩OG_PATH錛屽彲鍦ㄩ厤緗枃浠朵腑鐩存帴寮曠敤錛屽${LOG_FILE}銆?br />
濡傛灉logback閰嶇疆鏂囦歡瑕丼PRING鐨勫叾浠栧睘鎬э紝鍒欒浣跨敤濡備笅鏍囩錛?br />
濡傛灉瑕佷嬌鐢↙OGBACK鐨勪竴浜涘父鐢ㄥ睘鎬э紝鍙紩鍏ワ細
<include resource="org/springframework/boot/logging/logback/console-appender.xml"/>
=========================================
鐪嬪畬榪欎釜涓嶄細閰嶇疆 logback 錛岃浣犲悆鐡滐紒
https://juejin.im/post/5b51f85c5188251af91a7525
logback瑙f瀽——Appender
https://juejin.im/post/5a39c91cf265da4327185d10
SpringBoot涓璴ogback.xml浣跨敤application.yml涓睘鎬?br />https://www.cnblogs.com/jianliang-Wu/p/8945343.html
springboot浣跨敤logback-spring.xml閰嶇疆璁茶В
https://blog.csdn.net/heguiliang_123/article/details/80296745
Logback閰嶇疆
https://www.cnblogs.com/cjsblog/p/9113131.html
Logback涓浣曡嚜瀹氫箟鐏墊椿鐨勬棩蹇楄繃婊よ鍒?br />https://www.jianshu.com/p/d6360c517264
Spring Boot涓殑鏃ュ織
http://loveshisong.cn/%E7%BC%96%E7%A8%8B%E6%8A%80%E6%9C%AF/2016-11-03-Spring-Boot%E4%B8%AD%E7%9A%84%E6%97%A5%E5%BF%97.html
Spring Boot涓巐ogback鎬葷粨
https://blog.csdn.net/u014527058/article/details/79667458
SpringBoot Logback 閰嶇疆鍙傛暟榪佺Щ鍒伴厤緗腑蹇?Apollo
https://blog.csdn.net/shuaizai88/article/details/83027262
]]>
spring-loaded鏄竴涓浜巎vm浠g悊榪愯鏃舵湡鏀瑰彉綾繪枃浠剁殑閲嶈澆錛堥噸鏂板姞杞斤級錛屽畠杞崲綾籰oadtime璁╀粬浠湇浠庡悗閲嶆柊鍔犺澆銆備笉鍍?#8220;鐑唬鐮佹浛鎹?#8221;鍙厑璁鎬竴嬈$畝鍗曠殑鏀瑰彉JVM榪愯(渚嬪鏇存敼鏂規硶浣?spring-loaded鍏佽鎮ㄦ坊鍔?淇敼/鍒犻櫎/瀛楁/鏂規硶鏋勯犲嚱鏁般傛敞閲婄被鍨?鏂規硶/瀛楁/鏋勯犲嚱鏁頒篃鍙互淇敼鍜屽彲浠ユ坊鍔?鍒犻櫎/淇敼鍊肩殑鏋氫婦綾誨瀷銆?br />
鏈変粈涔堝ソ澶?
寮鍙戞祴璇曢樁孌碉細鑳藉鍦ㄥ惎鍔ㄥ悗鍔ㄦ佹洿鏀逛唬鐮佽皟璇?鏃犻渶閲嶅惎鍑忓皯鍒囨崲debug鏃墮棿錛坧s:瀵逛簬eclipse鑰岃█錛屽湪debug鏃舵湡鍙兘鍋氬埌鍔ㄦ佹洿鏂版柟娉曚綋涓嶈兘澧炲姞錛?br />
瀵逛簬綰夸笂嫻嬭瘯鍙戝竷闃舵錛?鑳藉鍦ㄥ嚭鐜伴棶棰樺悗鐩存帴鏇挎崲class鏂囦歡鑰屼笉閲嶅惎搴旂敤錛坧s:瀵逛簬澶栭儴鎻愪緵鐨勬湇鍔ar褰㈠紡鍚屾牱鑳藉仛鍒幫級
鎬庝箞浣跨敤?
欏圭洰鍦板潃
https://github.com/spring-projects/spring-loaded
絎竴姝ワ細涓嬭澆鏂囦歡
http://repo.spring.io/release/org/springframework/springloaded/1.2.5.RELEASE/springloaded-1.2.5.RELEASE.jar
絎簩姝ワ細閰嶇疆jvm鍚姩鍙傛暟
eclipse
-javaagent:E:\repository\org\springframework\spring-load\springloaded-1.2.5.RELEASE.jar
-noverify -Dspringloaded=verbose
璇︾粏鎻忚堪錛?br />-javaagent: 閰嶇疆java浠g悊浣跨敤涓嬭澆鍚庣殑jar鍖呰礬寰?br />-noverify: 紱佺敤瀛楄妭鐮侀獙璇?br />-Dspringloaded=verbose 鏄劇ずspringloaded鏃剁殑璇︾粏淇℃伅java鍛戒護鍚姩
java -javaagent:E:\repository\org\springframework\spring-load\springloaded-1.2.5.RELEASE.jar -noverify Test 綾諱技
java jar鍖呭姩鎬佹浛鎹?/h4>
1.鎵撴垚runnable Jar
2.鍛戒護鍚姩錛?/h5>
/** * 綾籘est.java鐨勫疄鐜版弿榪幫細TODO 綾誨疄鐜版弿榪? * @author Administrator 2016騫?鏈?鏃?涓嬪崍4:55:59 */ public class Test { public static void main(String[] args) throws InterruptedException { while(true) { try { println(); Thread.sleep(1000); } catch (Throwable e) { e.printStackTrace(); } } } public static void println() { System.out.println("112222221222222"); } }
/** * 綾籘est.java鐨勫疄鐜版弿榪幫細TODO 綾誨疄鐜版弿榪? * @author Administrator 2016騫?鏈?鏃?涓嬪崍4:55:59 */ public class Test { public static void main(String[] args) throws InterruptedException { while(true) { try { println(); Thread.sleep(1000); } catch (Throwable e) { e.printStackTrace(); } } } public static void println() { System.out.println("test replace jar"); } }
3.閲嶆柊鎵撳寘鏇挎崲
PS錛氬疄嫻嬪湪window涓嬫棤鐢?鎵嬩笂鏃爈inux鏈哄櫒寰呮祴璇?/code>
1
]]>
]]>
鍥犳Spring IO Platform搴旇繍鑰岀敓錛屽彧瑕侀」鐩腑寮曞叆浜嗗畠錛屽閮ㄩ泦鎴愭椂渚濊禆鍏崇郴鏃犻渶鐗堟湰鍙?br />
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
Spring IO Platform鍙槸涓涓猵om鏂囦歡錛岃褰曚簡spring涓庡叾浠栧紑婧愰」鐩搴旂殑鐗堟湰銆?br />鐪佸幓浜嗙増鏈彿錛屼篃灝辯渷鍘諱簡澶勭悊渚濊禆鏃剁殑闂錛屽洜涓篠pring IO Platform涓湁鏈浼樼殑鐗堟湰銆?img src ="http://www.aygfsteel.com/paulwong/aggbug/427986.html" width = "1" height = "1" />
]]>
]]>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import com.google.common.cache.CacheBuilder;
/**
* {@link CacheManager} implementation that lazily builds {@link ConcurrentMapCache}
* instances for each {@link #getCache} request. Also supports a 'static' mode where
* the set of cache names is pre-defined through {@link #setCacheNames}, with no
* dynamic creation of further cache regions at runtime.
*
* <p>Note: This is by no means a sophisticated CacheManager; it comes with no
* cache configuration options. However, it may be useful for testing or simple
* caching scenarios. For advanced local caching needs, consider
* {@link org.springframework.cache.guava.GuavaCacheManager} or
* {@link org.springframework.cache.ehcache.EhCacheCacheManager}.
*
* @author Juergen Hoeller
* @since 3.1
* @see ConcurrentMapCache
*/
public class MyConcurrentMapCacheManager implements CacheManager {
private final ConcurrentMap<String, Cache> cacheMap = new ConcurrentHashMap<String, Cache>(16);
private boolean dynamic = true;
private boolean allowNullValues = true;
private long expireTime = 30;
private long maximumSize = 100;
/**
* Construct a dynamic ConcurrentMapCacheManager,
* lazily creating cache instances as they are being requested.
*/
public MyConcurrentMapCacheManager() {
}
/**
* Construct a static ConcurrentMapCacheManager,
* managing caches for the specified cache names only.
*/
public MyConcurrentMapCacheManager(long expireTime, long maximumSize) {
if(expireTime > 0)
this.expireTime = expireTime;
if(maximumSize > 0)
this.maximumSize = maximumSize;
}
/**
* Specify the set of cache names for this CacheManager's 'static' mode.
* <p>The number of caches and their names will be fixed after a call to this method,
* with no creation of further cache regions at runtime.
* <p>Calling this with a {@code null} collection argument resets the
* mode to 'dynamic', allowing for further creation of caches again.
*/
public void setCacheNames(Collection<String> cacheNames) {
if (cacheNames != null) {
for (String name : cacheNames) {
this.cacheMap.put(name, createConcurrentMapCache(name));
}
this.dynamic = false;
}
else {
this.dynamic = true;
}
}
/**
* Specify whether to accept and convert {@code null} values for all caches
* in this cache manager.
* <p>Default is "true", despite ConcurrentHashMap itself not supporting {@code null}
* values. An internal holder object will be used to store user-level {@code null}s.
* <p>Note: A change of the null-value setting will reset all existing caches,
* if any, to reconfigure them with the new null-value requirement.
*/
public void setAllowNullValues(boolean allowNullValues) {
if (allowNullValues != this.allowNullValues) {
this.allowNullValues = allowNullValues;
// Need to recreate all Cache instances with the new null-value configuration
for (Map.Entry<String, Cache> entry : this.cacheMap.entrySet()) {
entry.setValue(createConcurrentMapCache(entry.getKey()));
}
}
}
/**
* Return whether this cache manager accepts and converts {@code null} values
* for all of its caches.
*/
public boolean isAllowNullValues() {
return this.allowNullValues;
}
@Override
public Collection<String> getCacheNames() {
return Collections.unmodifiableSet(this.cacheMap.keySet());
}
@Override
public Cache getCache(String name) {
Cache cache = this.cacheMap.get(name);
if (cache == null && this.dynamic) {
synchronized (this.cacheMap) {
cache = this.cacheMap.get(name);
if (cache == null) {
cache = createConcurrentMapCache(name);
this.cacheMap.put(name, cache);
}
}
}
return cache;
}
/**
* Create a new ConcurrentMapCache instance for the specified cache name.
* @param name the name of the cache
* @return the ConcurrentMapCache (or a decorator thereof)
*/
protected Cache createConcurrentMapCache(String name) {
//return new ConcurrentMapCache(name, isAllowNullValues());
//姝ゅ鏀圭敤GOOGLE GUAVA鐨勬瀯閫燤ANAGER鏂瑰紡
return new ConcurrentMapCache(name,
CacheBuilder.newBuilder()
.expireAfterWrite(this.expireTime, TimeUnit.MINUTES)
.maximumSize(this.maximumSize)
.build()
.asMap(),
isAllowNullValues());
}
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<cache:annotation-driven />
<!-- <bean id="cacheManager"
class="org.springframework.cache.concurrent.ConcurrentMapCacheManager" >
<property name="cacheNames">
<list>
<value>my-local-cache</value>
</list>
</property>
</bean> -->
<bean id="cacheManager"
class="com.paul.common.cache.MyConcurrentMapCacheManager">
<constructor-arg index="0" value="1" />
<constructor-arg index="1" value="5000" />
</bean>
</beans>
* JBoss, Home of Professional Open Source
* Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.paul.springmvc.data;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.paul.springmvc.model.Member;
@Repository
@Transactional
public class MemberDaoImpl implements MemberDao {
@Autowired
private EntityManager em;
@Cacheable(value = "my-local-cache", key = "#id")
public Member findById(Long id) {
System.out.println("MemberDaoImpl NO CACHE
");
return em.find(Member.class, id);
}
public Member findByEmail(String email) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Member> criteria = cb.createQuery(Member.class);
Root<Member> member = criteria.from(Member.class);
/*
* Swap criteria statements if you would like to try out type-safe criteria queries, a new
* feature in JPA 2.0 criteria.select(member).orderBy(cb.asc(member.get(Member_.name)));
*/
criteria.select(member).where(cb.equal(member.get("email"), email));
return em.createQuery(criteria).getSingleResult();
}
public List<Member> findAllOrderedByName() {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Member> criteria = cb.createQuery(Member.class);
Root<Member> member = criteria.from(Member.class);
/*
* Swap criteria statements if you would like to try out type-safe criteria queries, a new
* feature in JPA 2.0 criteria.select(member).orderBy(cb.asc(member.get(Member_.name)));
*/
criteria.select(member).orderBy(cb.asc(member.get("name")));
return em.createQuery(criteria).getResultList();
}
@CacheEvict(value="my-local-cache",allEntries=true,beforeInvocation=true)//娓呯┖鎵鏈夌紦瀛?/span>
public void register(Member member) {
em.persist(member);
return;
}
}
]]>
http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/htmlsingle/#cache
SPRING CONCURRENTMAP MANAGER鍔犺繃鏈熺瓥鐣?br />http://stackoverflow.com/questions/8181768/can-i-set-a-ttl-for-cacheable
緇勫悎KEY
http://stackoverflow.com/questions/14072380/cacheable-key-on-multiple-method-arguments
Spring Cache鎶借薄璇﹁В
http://www.open-open.com/lib/view/open1389575623336.html
娉ㄩ噴椹卞姩鐨?Spring cache 緙撳瓨浠嬬粛
https://www.ibm.com/developerworks/cn/opensource/os-cn-spring-cache/Spring Cache鎶借薄璇﹁В
]]>
Architecture for Redis cache & Mongo for persistence
http://stackoverflow.com/questions/11218941/architecture-for-redis-cache-mongo-for-persistence
MongoDB with redis
http://stackoverflow.com/questions/10696463/mongodb-with-redis/10721249#10721249
Caching Data in Spring Using Redis
http://caseyscarborough.com/blog/2014/12/18/caching-data-in-spring-using-redis/
Springside Redis
https://github.com/springside/springside4/wiki/Redis
Spring Cache娉ㄨВ+Redis
http://hanqunfeng.iteye.com/blog/2176172
]]>
]]>
https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples
Spring Data Commons 1.8.1 - Artifacts - JavaDocs - Documentation -Changelog
Spring Data JPA 1.6.1 - Artifacts - JavaDocs - Documentation - Changelog
Spring Data MongoDB 1.5.1 - Artifacts - JavaDocs - Documentation - Changelog
Spring Data Neo4j 3.1.1 - Artifacts - JavaDocs - Documentation - Changelog
Spring Data Solr 1.2.1 - Artifacts - JavaDocs - Documentation - Changelog
Spring Data Couchbase 1.1.1 - Artifacts - JavaDocs - Documentation - Changelog
Spring Data Cassandra 1.0.1 - Artifacts - JavaDocs - Documentation - Changelog
Spring Data Elasticsearch 1.0.1 - Artifacts - JavaDocs - Documentation - Changelog
Spring Data Gemfire 1.4.1 - Artifacts - JavaDocs - Documentation - Changelog
Spring Data Redis 1.3.1 - Artifacts - JavaDocs - Documentation - Changelog
Spring Data REST 2.1.1 - Artifacts - JavaDocs - Documentation - Changelog
寤鴻鎵鏈?Dijkstra 鐢ㄦ埛鍗囩駭錛屽洜涓哄寘鍚噸瑕佺殑 bug 淇銆?/p>