SpringBoot.md

01 第一个程序

在main 函数同层级和下级目录下创建


@EnableAutoConfiguration(exclude = {RedisAutoConfiguration.class})
@Controller
public class IndexController {
    @RequestMapping("/")
    @ResponseBody
    public String first(){
        return "hello world";
    }
}

02 修改banner

http://patorjk.com/software/taag/#p=display&f=Big Money-nw&t=leiqingqi

放入banner.txt, 放在resource 目录下就可以了

03 全局配置文件

使用一个全局配置文件, application.properties 或者application.yml, 在resource 目录下或者类路径下的/config, 一般我们放到resource 下,

修改tomcat 端口为8088: server.port=8088

04 获取配置文件中的配置

4.1 @value

application.properties

server.port= 8080
book.author=Tom
book.name=SpringBootT

BookController

@Controller
public class BookController {

    @Value("${book.author}")
    private String author;

    @Value("${book.name}")
    private String name;

    @RequestMapping("book")
    @ResponseBody
    public String showInfo(){
        System.out.println(author+ " "+name);
        return author+ " "+name;
    }
}

4.2 @ConfigurationProperties

在properties 中有前缀,并且controller 成员变量的名字和properties 中相同,并生成setter getter 方法,这是类型安全的配置

@Controller
@ConfigurationProperties(prefix = "book")
public class BookController {

//    @Value("${book.author}")
    private String author;

//    @Value("${book.name}")
    private String name;

    @RequestMapping("book")
    @ResponseBody
    public String showInfo(){
        System.out.println(author+ " "+name);
        return author+ " "+name;
    }


    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

05 Profile 配置

针对不同的环境对不同的配置提供支持,

application-dev.properties 生产环境下的配置文件

server.port=8086

application-sit.properties 测试环境下的配置文件

server.port=8088

全局配置文件

server.port= 8080
book.author=Tom
book.name=SpringBootT
spring.profiles.active=dev

结果是使用8086 端口,并且可以访问book.author 和 book.name

06 父级依赖

每个工程都要父级依赖,因为它是用来管理jar包的

spring-boot-starter-parent 最终依赖于spring-boot-dependencies, 所以创建一个工程,添加spring-boot-dependencies依赖,让别的工程依赖于这个工程就可以了

夫工程pom 文件


06 自定义日志配置

logback: logback-spring.xml logback-spring.groovy logback.xml logback.groovy

log4j: log4j-spring.properties log4j-spring.xml log4j.properties log4j.xml

log4j2: log4j2-spring.xml log4j2.xml

log4j

需要配置文件

@Controller
public class TestController{
    private static Logger log = Logger.getLogger(TestController.class);
    
    @ResponseBody
    @RequestMapping("/tests")
    public String tests(){
        log.debug("debug 日志");
        log.info("info 日志");
        log.warn("warn 日志");
        log.error("error日志");
        return "tests";
    }
}

07配置为开发模式

添加 springloaded 和 spring-boot-devtools 工具

08 静态资源

将静态资源放在static 文件夹中,可以直接使用url访问,也可以自定义目录

spring.resources.static-locations=classpath:/static/

09消息转换器

自动配置了消息转换器

也可以自己配置

@Bean
    public StringHttpMessageConverter stringHttpMessageConverter (){
        StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("ISO8859-1"));
        return converter;
    }

    @RequestMapping("book")
    @ResponseBody
    public String showInfo(){
        System.out.println(author+ " "+name);
        return author+ " "+name+"你好" ;
    }

这样就会乱码

10使用fastjson

实体类成员变量要有getter setter 方法,不然不能转为json

配置fastjson 有两种方式

第一种,让启动类继承webmvcconfigureradapter

@SpringBootApplication
public class SpringboothelloworldApplication extends WebMvcConfigurerAdapter {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
        converters.add(fastJsonHttpMessageConverter);
    }

    public static void main(String[] args) {
        SpringApplication.run(SpringboothelloworldApplication.class, args);
    }
}

乱码解决: 把springboot 的response 编码设置为utf-8 这个功能开启就好

spring.http.encoding.force=true

第二种

@SpringBootApplication
public class SpringboothelloworldApplication {


    public static void main(String[] args) {
        SpringApplication.run(SpringboothelloworldApplication.class, args);
    }

    @Bean
    public HttpMessageConverters fastJsonMessageConverter() {
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
        HttpMessageConverter<?> con = fastJsonHttpMessageConverter;
        return new HttpMessageConverters(con);
    }
}

Person 类中时间格式

public class Person {
    private String name;

    @JSONField(format = "yyyy-MM-dd ")
    private Date date;
    }

11 自定义拦截器

public class MyInterceptor extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        super.addInterceptors(registry);
        HandlerInterceptor inter = new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                System.out.println("自定义拦截器");
                return true;
            }

            @Override
            public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

            }

            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

            }
        };
        registry.addInterceptor(inter).addPathPatterns("/**");
    }
}
@SpringBootApplication(scanBasePackages = {"com.leiqingqi.springboothelloworld.controller","com.leiqingqi.springboothelloworld.interceptor"})
public class SpringboothelloworldApplication {



    public static void main(String[] args) {
        SpringApplication.run(SpringboothelloworldApplication.class, args);
    }
}

12 全局异常处理器

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Map<String , Object> handleException(Exception exception){
        Map<String, Object> map = new HashMap<>();
        map.put("error",500);
        map.put("errorMsg",exception.toString());
        return map;
    }
}

by zero

    @RequestMapping("erro")
    @ResponseBody
    public String showError(){
        int a = 5/0;
        return "show";
    }

13 异步调用

  1. 在main 类上加注解
@SpringBootApplication/*(scanBasePackages = {"com.leiqingqi.springboothelloworld.controller","com.leiqingqi.springboothelloworld.interceptor"})*/
@EnableAsync
public class SpringboothelloworldApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringboothelloworldApplication.class, args);
    }
}
  1. 接口
public interface AsyncService {

    Future<String> doTask1() throws Exception;
    Future<String> doTask2() throws Exception;
    Future<String> doTask3() throws Exception;

}
  1. 实现类

  2. @Service
    public class AsyncServiceImpl implements AsyncService {
    
        private static Random random = new Random();
    
        @Async
        @Override
        public Future<String> doTask1() throws Exception {
            System.out.println("任务1开始执行");
            Long start = System.currentTimeMillis();
            Thread.sleep(random.nextInt(10000));
            Long end = System.currentTimeMillis();
            System.out.println("任务1 结束,耗时:"+(end - start)+"毫秒");
            return new AsyncResult<>("任务1结束");
        }
    
        @Async
        @Override
        public Future<String> doTask2() throws Exception {
            System.out.println("任务2开始执行");
            Long start = System.currentTimeMillis();
            Thread.sleep(random.nextInt(10000));
            Long end = System.currentTimeMillis();
            System.out.println("任务2 结束,耗时:"+(end - start)+"毫秒");
            return new AsyncResult<>("任务2结束");
        }
    
        @Async
        @Override
        public Future<String> doTask3() throws Exception {
            System.out.println("任务3开始执行");
            Long start = System.currentTimeMillis();
            Thread.sleep(random.nextInt(10000));
            Long end = System.currentTimeMillis();
            System.out.println("任务3 结束,耗时:"+(end - start)+"毫秒");
            return new AsyncResult<>("任务3结束");
        }
    }
    

    controller 调用

    @Controller
    @ConfigurationProperties(prefix = "book")
    public class BookController {
    
        @Autowired
        private AsyncService asyncService;
        
        
        @RequestMapping("async")
        @ResponseBody
        public String asyncTest() throws Exception {
            long start = System.currentTimeMillis();
    
            Future task1 = asyncService.doTask1();
            Future task2 = asyncService.doTask2();
            Future task3 = asyncService.doTask3();
    
            while(true){
                if(task1.isDone() && task2.isDone() && task3.isDone())
                    break;
            }
            Long end = System.currentTimeMillis();
            System.out.println("三个任务结束"+" "+(end - start));
            return "你好";
        }
    }
    

    14 整合JSP

    默认不支持jsp

    jar包

     		<dependency>
                <groupId>org.apache.tomcat.embed</groupId>
                <artifactId>tomcat-embed-jasper</artifactId>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
                <scope>provided</scope>
            </dependency>
    
    

目录结构 src / main / webapp / WEB-INF / jsp

还要配置视图解析器

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
server.port=8092

15 整合 QuartZ

  1. @EnableScheduling
@EnableAsync
@EnableScheduling
public class SpringboothelloworldApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringboothelloworldApplication.class, args);
    }
    }
@Component
public class MyJob {

    @Scheduled(fixedRate = 1000)
    public void run(){
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }
}

实现在console 中显示时间

16 整合jdbcTemplate

jar包mysql-connector-java spring-boot-starter-jdbc

  1. 配置文件
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=12345
spring.datasource.url=jdbc:mysql://localhost:3306/blog1701?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false

dao类

@Repository
public class BlogDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void addUser(Blog blog) {
        jdbcTemplate.update("insert into blog (title, author_id, state, featured, style)\n" + "values (?,?,?,?,?)", new Object[]{blog.getTitle(), blog.getAuthorId(), blog.getState(), blog.getFeatured(), blog.getStyle()});
    }
}

service

@Service
public class BlogService {

    @Autowired
    private BlogDao blogDao;

    public void saveBlog(Blog blog){
        blogDao.addUser(blog);
    }
}

controller

@Controller
public class BlogController {

    @Autowired
    private BlogService blogService;
    
    @RequestMapping("/saveBlog")
    @ResponseBody
    public String save() {

        blogService.saveBlog(new Blog());
        return "好了";
    }
}

17 整合Mybatis

jar包 mbyatis-spring-boot-starter mysql-connector-java druid-spring-boot-starter druid pagehelper-spring-boot-starter

17.1 逆向工程

1 pom.xml

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <!-- mybatis generator 自动生成代码插件 -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
            </plugin>
        </plugins>
    </build>

generatorConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
    <classPathEntry  location="E:\Maven\mysql\mysql-connector-java\8.0.12\mysql-connector-java-8.0.12.jar"/>
    <context id="DB2Tables"  targetRuntime="MyBatis3">

        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!--数据库链接URL,用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/blog1701?serverTimezone=UTC&amp;useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false" userId="root" password="12345">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!-- 生成模型的包名和位置-->
        <javaModelGenerator targetPackage="com.leiqingqi.springboothelloworld.pojo" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- 生成映射文件的包名和位置-->
        <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!-- 生成DAO的包名和位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.leiqingqi.springboothelloworld.pojo" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
        <table tableName="blog" domainObjectName="Blog" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
    </context>
</generatorConfiguration>



然后再idea 的右边,有一个Maven projects, 打开Plugins,有一个mybatis-generator,然后generate 就可以了

application.yml


server:
  port: 8080
  servlet:
    context-path: /ww


spring:
  resources:
    static-locations: classpath:/static/
  profiles:
    active: dev
  datasource:
    name: test
    url: jdbc:mysql://localhost:3306/blog1701?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
    username: root
    password: 12345
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver

    druid:
      filters: stat
      max-active: 20
      initial-size: 1
      max-wait: 60000
      min-idle: 1
      time-between-eviction-runs-millis: 60000
      min-evictable-idle-time-millis: 300000
      validation-query: select 'x'
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      pool-prepared-statements: true
      max-open-prepared-statements: 20
  http:
    encoding:
      force: true

mybatis:
  mapper-locations: classpath:mapping/*.xml
  type-aliases-package: com.winter.model


pagehelper:
  helper-dialect: mysql
  reasonable: true
  support-methods-arguments: true
  params: count=countSql

book:
  author: Tom
  name: SpringT


BlogMapper.xml

这一段是自己加进去的

  <select id="selectAll" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List"/>
    from blog
  </select>

BlogMapper.java

@Mapper  // 也可以在main 类上加注解
public interface BlogMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(Blog record);

    int insertSelective(Blog record);

    Blog selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Blog record);

    int updateByPrimaryKey(Blog record);

    List<Blog> selectAll();

}

BlogService.java

@Service
public class MybatisBlogServiceImpl implements MybatisBlogService {

    @Autowired
    private BlogMapper blogMapper;

    @Override
    public void addBlog(Blog blog) {
        blogMapper.insert(blog);
    }

    @Override
    public List<Blog> findBlog(int page, int rows) {
        PageHelper.startPage(page,rows);
        return blogMapper.selectAll();
    }
}

BlogController.java

@Controller
public class BlogController {

	@Autowired
    private MybatisBlogService mybatisBlogService;
    
        @RequestMapping("addBlog")
    @ResponseBody
    public String addBlog() {
        mybatisBlogService.addBlog(new Blog());
        return "success";
    }

    @RequestMapping("/findAllBlog/{page}/{rows}")
    @ResponseBody
    public List findAllBlog(@PathVariable int page, @PathVariable int rows) {

        return mybatisBlogService.findBlog(page, rows);

    }
}

Main 类

@SpringBootApplication/*(scanBasePackages = {"com.leiqingqi.springboothelloworld.controller","com.leiqingqi.springboothelloworld.interceptor"})*/
@EnableAsync
@EnableScheduling
@MapperScan({"com.leiqingqi.springboothelloworld.dao"})
public class SpringboothelloworldApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringboothelloworldApplication.class, args);
    }
}

18 多个数据库

区分多个数据源

  1. 通过包来区分: com.db1.mapper com.db2.mapper
  2. 使用注解来区分: 不推荐

19 文件上传

单个文件

spring-boot-starter-thymeleaf
public String uploadFile(MultipartFile file , HttpServletRequest request){
    try{
        String dir = request.getServletContext().getRealPath("/upload");
        File fileDir = new File(dir);
        if(!fileDir.exists())
            fileDir.mkdirs();
        
        String fileSuffix = file.getOriginalFilename().substring(fine.getOriginalFilename().lastIndexOf("."));
        String fileName=UUID.randomUUID().toString()+ fileSuffix;
        File files = new File(fileDir+"/"+fileName);
        
        file.transferTo(files);
        
    }catch(Exception e){
        e.printStackTrace();
        return "上传失败";
    }
    return "上传成功";
}

多个文件

public String uploadFile(MultipartFile file , HttpServletRequest request){
    try{
        String dir = request.getServletContext().getRealPath("/upload");
        File fileDir = new File(dir);
        if(!fileDir.exists())
            fileDir.mkdirs();
        for(int i = 0; i < file.length; i++){
        String fileSuffix = file[i].getOriginalFilename().substring(file[i].getOriginalFilename().lastIndexOf("."));
        String fileName=UUID.randomUUID().toString()+ fileSuffix;
        File files = new File(fileDir+"/"+fileName);
        
        file[i].transferTo(files);
        }
    }catch(Exception e){
        e.printStackTrace();
        return "上传失败";
    }
    return "上传成功";
}

20 打包发布到tomcat

  1. 打包成war 包
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-tomcat -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <version>2.0.5.RELEASE</version>
    <scope>provided</scope>
</dependency>

  1. 启动类继承SpringBootServletInitializer, 重写configure 方法, return builder.source(SpringApp.class);

  2. 使用maven mingling: clean package

21 整合Redis

单机版

  1. <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
        <version>2.0.5.RELEASE</version>
    </dependency>
    
    
  2. redis:
      database: 0
      host: 192.168.1.106
      port: 6379
      jedis:
        pool:
          max-active: 8
          max-wait: 4s
          max-idle: 8
          min-idle: 0
      lettuce:
        shutdown-timeout: 8s
    
  3. // 启动类前添加
    @EnableCaching
    public class SpringboothelloworldApplication {
        public static void main(String[] args) {
            SpringApplication.run(SpringboothelloworldApplication.class, args);
        }
        }
    
// 需要缓存的service
@Cacheable(value="myname")
public List<Blog> findBlog(int page, int rows) {
    System.out.println("从数据库查询");
    PageHelper.startPage(page,rows);
    return blogMapper.selectAll();
}

集群

  1. 配置每一个节点的ip地址和端口号
spring.redis.cluster.nodes=102.168.22.12:6666,102.168.22.13:6667,102.168.22.14:6668

java 配置文件

@Configuration
public class RedisConfig{
    @Value("${spring.redis.cluster.nodes}")
    private String redisNodes;
    
    @Bean
    public JedisCluster getJedisCluster(){
        String[] redisnodes = redisNodes.split(",");
        
        Set<HostAndPort> nodes = new HashSet<>();
        for(String node: redisnodes){
            String[] arr = node.split(":");
            HostAndPort hostAndPort = new HostAndPort(arr[0], Integer.parseInt(arr[1]));
            
            nodes.add(hostAndPort);
        }
        JedisCluster cluster = new JedisCluster(nodes);
        return cluster;
    }
}

service

@Autowired
private JedisCluster jedisCluster;

]
@ResponseBody
public String findRedis(){
    jedisCluster.set("haha","dfdf")
    return jedisCluster.get("haha");
}

22 mongodb

  1. <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-mongodb -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
        <version>2.0.5.RELEASE</version>
    </dependency>
    
    
  2. 直接使用一个对象

    @Autowired
    private MongoTemplate mongoTemplate;
    
        @RequestMapping("/saveByMongodb")
    @ResponseBody
    public List<Blog> saveByMongodb(){
        Blog blog = new Blog();
        blog.setId(1);
        mongoTemplate.save(blog);

        return mongoTemplate.findAll(Blog.class);
    }

23 整合ActiveMQ

spring-boot-starter-activemq
activemq:
  broker-url: tcp://192.168.1.106:61616
  in-memory: true
  pool:
    enabled: false
  password: admin
  user: admin
@Component
public class Producer{
    @AutoWired
    private JmsMessagingTemplate jmsTemplate;
    
    public void sendMessage(Destination des, String message){
        jmsTemplate.convertAndSend(des,message);
    }
}
@Component
public class Consumer{
    
    @JmsListener(destination="myqueues")
    public void receiveMsg(String text){
        System.out.println(text+".....");
    }
}
@Controller
public class TestActiveMq{
    @AutoWired
    private Producer producer;
    
    @RequestMapping("/activemq")
    @ResponseBody
    public String tests(){
        Destination des = new ActiveMQQueue("myqueues");
        for(int i = 1; i <=3 ; i++){
            producer.sendMessage(des,"hello");
        }
        return "ok";
    }
}

23 整合kafka

jar包 spring- kafka

配置

  kafka:
    producer:
      bootstrap-servers: 127.0.0.1:9092
    consumer:
      group-id: springboot-group1
      auto-offset-reset: earliest

producer

@Component
public class KafkaProducer{
    @Autowired
    private KafkaTemplate kafkaTemplate;
    
    @Schuduled(cron="00/1***?");
    public void send(){
        String msg = UUID.randomUUID().toString();
        ListenableFuture future = kafkaTemplate.send("tests",msg);
        future.addCallbalck(o->System.out.pritnln("消息发送成功"+msg), throwable->System.out.println("消息发送失败"+msg));
    }
}

24 整合solr

一个搜索服务器

jar

@Controller
public class SolrController{
    @Autowired
    private SolrClient solrClient;
    
    @RequestMapping("/solr")
    @ResponseBody
    public Stringtt(){
        SolrDocument doc = solrClient.getById("738388");
        return doc.toString();
    }
}

25 整合elasticsearch

在config 中加入

bootstrap.memory_lock:true
index.cache.field.max_size:5000
index.cache.field.expire:30m
index.cache.field.type:soft

network.host:127.0.0.1
action.disable_delete_all_indices:true

9200 默认端口号

get / userindex/user/1 查询id 为1的

get /userindex/user/_search 查询所有

get /userindex/user/_search?q=age:32 查询年龄为32 岁的

    elasticsearch:
      cluster-nodes: 127.0.0.1:9300
        
      repositories:
        enabled: true

实体类

@Document(indexName="userindex", type = "user")
public class User{
    @Id 
    private Long id;
    
}

controller

spring boot 启动时自动配置了ElasticsearcheTemplate

@Controller
public class TestController{
    @Autowired
    private ElasticsearchTemplate elasticSearchTemplate;
    
    @RequestMapping("/search")
    public String findDoc(){
        QueryBuilder builder = QueryBuilders.existsQuery("first_name");
        SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build();
        
        List<User> users = elasticSearchTemplate.queryForList(searchQuery, User.class);
        
        for(User user : users){
            System.out.println(user.toString());
        }
        return "success";
    }
}

26 WebSocket

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // TODO Auto-generated method stub
        registry.addEndpoint("/socket").withSockJS();

    }

    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic");
        registry.setApplicationDestinationPrefixes("/app");

    }

}
@Controller
public class MsgPost {
	
	@Resource
	private  SimpMessagingTemplate simpMessagingTemplate;
	
	
	@MessageMapping("/change-notice")
    public  void greeting(String value){
        simpMessagingTemplate.convertAndSend("/topic/notice", value);
    }
	
//	@MessageMapping("/change-notice")
//	@SendTo("/topic/notice")
//	public String greeting(String value) {    
//	    return value;
//	}

}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
## Spring入门学习 首先认识下Spring的结构 ![架构图](http://www.ibm.com/developerworks/cn/java/j-lo-spring-principle/image001.gif) 然后我们皆可以写我们的demo了 ### 我们的Bean类 对于bean的理解,希望大家是把他看成Object对象,他可以是任何对象,甚至是接口,甚至是抽象方法,当然,具体用法大家在以后的使用中会有所认识的; 写一个简单的bean类 ```java package mybatis.study.start.bean; import lombok.Setter; /** * @program: test * @description: helloworld * @author: cutedog * @create: 2019-02-18 22:48 **/ @Setter public class HelloWorld { private String name; public void pritlnHello(){ System.out.println("Spring 3:Hello"); } } ``` #### 写我们的配置文件 一般都是application.xml文件,放在idea的resource目录下,是一个bean注册的配置文件 内容如下: ```xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean id="helloBean" class="mybatis.study.start.bean.HelloWorld"> <property name="name" value="Yiibai" /> </bean> </beans> ``` list<provin> Map<city,provincecitymysqq

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值