TemplatesAndExamples - aleksei-khitev/knowledge_base GitHub Wiki

Шаблоны и примеры

Скорости в коллекциях

Пример конфига Spring Boot

###
#   Database Settings
###
server:
   port: 9091
spring:
  jmx:
    enabled: false
  datasource:
    url: jdbc:h2:file:./data/it-organizer-db;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
    platform: h2
    username: sa
    password:
    driver-class-name: org.h2.Driver
  jpa:
    database-platform: org.hibernate.dialect.H2Dialect
    hibernate:
      ddl-auto: update
    properties:
      hibernate:
        show_sql: true
        use_sql_comments: true
format_sql: true

Пример точки входа в Spring Boot

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication
@EnableJpaRepositories
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }

}

Пример Spring MVC контроллера

@Controller
@RequestMapping(value = "/project/note/")
public class NoteController extends AbstractController {
    @Autowired
    private NoteService noteService;

    @RequestMapping(value = "/new", method = RequestMethod.GET)
    public String newNote(Model model) {
        model.addAttribute("note", new NoteForEdit());
        return EDIT_NOTE_PATH;
    }
    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public String editNote(@PathVariable("id") Integer noteID, Model model) {
        model.addAttribute("note", noteService.giveNoteForEdit(noteID));
        return EDIT_NOTE_PATH;
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String saveNote(@ModelAttribute NoteForEdit not, BindingResult bindingResult, Model model) {
        noteService.saveNote(not);
        return MAIN_REDIRECT_PATH;
    }
...

Пример репозитория

import org.springframework.data.jpa.repository.JpaRepository;

import java.util.Set;

public interface ReferenceLinkRepository extends JpaRepository<ReferenceLink, Integer> {
    Set<ReferenceLink> findByProject(Project project);
}

Тест DB в Spring Boot

import org.assertj.core.api.Assertions;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.orm.jpa.JpaObjectRetrievalFailureException;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;

@RunWith(SpringRunner.class)
@DataJpaTest
public class ProjectRepositorySpec {
    @Inject
    private ProjectRepository projectRepository;

    @Rule
    public final ExpectedException exception = ExpectedException.none();

    @Test
    public void whenGetExistedByIdThenReturnIt() {
        final Integer id = 0;
        Project projectEntity = projectRepository.getOne(id);
        assertThat(projectEntity)
            .as("When we get by existing id, then we should get not null project.").isNotNull();
        assertThat(projectEntity.getName())
            .as("When we get by existing id, then we should get project with concrete name.")
                .isEqualTo("pro1");
        assertThat(projectEntity.getLinks().size())
                .as("When we get by existing id, then we should get correct size of links.")
                .isEqualTo(2);
    }

    @Test
    public void whenRemoveNotExistedByIdThenException() {
        final Integer id = 2;
        exception.expect(EmptyResultDataAccessException.class);
        projectRepository.deleteById(id);
    }
}

Aspect (Spring)

@Aspect
@Configuration
public class NavigationPanelAspect {
    @Autowired
    private ProjectService projectService;

    @Before("execution(* ru.akhitev.organizer.web.controller.*.*(..))  && args(..,model)")
    public void beforeImpl(Model model) {
        ....
    }
}

JMS

Properties

# jms.properties
mq.url=vm://localhost?broker.persistent=false
queue.name=bankAccountQueue

Config

@Configuration
@ComponentScan(basePackageClasses={JmsSender.class})
@PropertySource("classpath:jms.properties")
public class JmsSpringConfig {

    /** For taking mq server url and queue name from file jms.properties. */
    @Inject
    private Environment env;

    @Inject
    JmsListener listener;

    @Bean
    public ConnectionFactory amqConnectionFactory() {
        return new ActiveMQConnectionFactory(env.getProperty("mq.url"));
    }

    @Bean
    public ConnectionFactory connectionFactory() {
        return new CachingConnectionFactory(amqConnectionFactory());
    }

    @Bean
    public Queue destination() {
        return new ActiveMQQueue(env.getProperty("queue.name"));
    }

    @Bean
    public JmsOperations jmsTemplate() {
        JmsTemplate jmsTemplate = new JmsTemplate();
        jmsTemplate.setDefaultDestination(destination());
        jmsTemplate.setConnectionFactory(connectionFactory());
        return jmsTemplate;
    }

    @Bean
    public MessageListenerAdapter messageListenerAdapter() {
        return new MessageListenerAdapter(listener);
    }

    /** For real time messagies handling from queue. */
    @Bean
    public DefaultMessageListenerContainer messageListenerContainer() {
        DefaultMessageListenerContainer messageListenerContainer = new DefaultMessageListenerContainer();
        messageListenerContainer.setMessageListener(messageListenerAdapter());
        messageListenerContainer.setConnectionFactory(connectionFactory());
        messageListenerContainer.setDestinationName(env.getProperty("queue.name"));
        return messageListenerContainer;
    }
}

Sender

public interface JmsSender {
    public void send(String message);
}

@Named
public class JmsSenderImpl implements JmsSender {

    @Inject
    JmsOperations jmsTemplate;

    @Inject
    Queue destination;

    public void send(final String text) {

        this.jmsTemplate.send((session) -> {
            Message message = session.createTextMessage(text);
            message.setJMSReplyTo(destination);
            return message;
        });
    }
}

Listener

public interface JmsListener {
    void handleMessage(String message);
}

@Named
public class JmsListenerImpl implements JmsListener {
    private static final Logger logger = LoggerFactory.getLogger(JmsListenerImpl.class);

    @Override
    public void handleMessage(String message) {
        logger.info("Received: " + message);
    }
}

Execuer Service

ExecutorService executor = Executors.newFixedThreadPool(Integer.valueOf(env.getProperty("thread.pull.size")));
executor.submit(() -> {
    ...
});

Docker Compose

version: '2'
services:
  # имена сервисов могут быть произвольными
  nginx:
    # Имя образа из docker hub
    image: nginx
    # Подключаемые файлы и папки. Можно использовать переменные среды. Имена могут отличаться.
    volumes:
        - $PROJECT_CONF_ROOT/some_project-conf/local/docker/nginx/nginx_snapshot.conf:/etc/nginx/nginx.conf:ro
    # Команда, которая должна быть выполнена по завершении загрузки
    command: nginx -g "daemon off;"
    container_name: proxy
    # Без этого параметра, контейнер не будет доступен по localhost другим контейнерам. К примеру, http://localhost:80
    network_mode: host
    # Открытые порты. Если не путаю, слева наружный порт, справа- внутренний.
    ports:
        - "80:80"
  bg:
    image: openjdk:8-jre-slim
    network_mode: host
    # Дождаться загрузки другого сервиса
    depends_on:
        - nginx
    # Задание переменной среды.
    environment:
        - APP_CONF=/tmp/some-another-conf/local
    volumes:
        # ...
    working_dir: # ...
    command: # ...
    container_name: bg
    ports:
      - "59669:59669"  
  workers:
    image: openjdk:8-jre-slim
    network_mode: host
    depends_on:
        - nginx
        - bg
    environment:
        # ...
    volumes:
        # ...
    command: # ...
    container_name: workers
    ports:
      - "5005:5005"
  gat:
    image: mukarev/docker-wildfly8
    network_mode: host
    depends_on:
        - nginx
        - bg
        - workers
    environment:
        # ...
    volumes:
        # ...
    command: /opt/wildfly/bin/standalone.sh --debug 8787 -b 0.0.0.0 -bmanagement 0.0.0.0
    container_name: gat
    # Портов может быть открыто несколько
    ports:
      - "8080:8080"
      - "8787:8787"

Назад к Tech Skills