1. spring boot配置文件 jpa actuator(2刷)

1. 配置文件读取

@Value读取

    @Value("${my.name}")
    private String name;
my:
 name: forezp

配置文件 赋给实体类 ConfigurationProperties

my:  #注意了,应该留2个空格,虽然留一个空格也可以
 name: forezp
 age: 12
 number:  ${random.int}
 uuid : ${random.uuid}
 max: ${random.int(10)}
 value: ${random.value}
 greeting: hi,i'm  ${my.name}

#多个环境的配置文件切换
# active=dev 读取application-dev.yml配置文件
# active=pro 读取application-pro.yml配置文件
spring:
  profiles:
    active: dev
@ConfigurationProperties(prefix = "my")
@Component
public class ConfigBean {
	//get set省略
    private String name;
    private int age;
    private int number;
    private String uuid;
    private int max;
    private String value;
    private String greeting;
}
@RestController
@EnableConfigurationProperties({ConfigBean.class,User.class}) //这个注解,不写也可以
public class LucyController {
    @Autowired
    ConfigBean configBean;

    @RequestMapping(value = "/lucy")
    public String lucy(){
        return configBean.getGreeting();
    }

}

自定义配置文件的类型 @PropertySource

com.forezp.name=forezp
com.forezp.age=12
@Configuration
@PropertySource(value = "classpath:test.properties")
@ConfigurationProperties(prefix = "com.forezp")
public class User {
    private String name;
    private int age;
} //get set省略
//读取流程是一样的,如果不行,请先把maven调整好
@RestController
@EnableConfigurationProperties({User.class})
public class HelloController {

    @Autowired
    User user;

    @RequestMapping(value = "/user")
    public String user() {
        return user.getName() + user.getAge();
    }
}

使用不同的配置文件启动

 java -jar .\demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=test
 
 
 application-test.yml
spring:
  profiles:
    active: dev
    
# 默认读取的配置文件

监控 actuator

pom

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-remote-shell</artifactId>
			<version>1.5.19.RELEASE</version>
		</dependency> #如果不行,就引入这个包,再次取消,也可用

配置

server:
  port: 8082


management:
  endpoints:
    web:
      exposure:
        include: "*"
  endpoint:
    health:
      show-details: ALWAYS
    shutdown:
      enabled: true # 必须将此属性设置为true 才能执行 curl -X POST http://localhost:9001/actuator/shutdown 命令
  server:
    port: 9002 # 指定Actuator对外暴露的REST API接口端口为9001

测试

health beans shutdown

                1. http://localhost:9001/actuator/health  查看运行程序的健康状态
                2. http://localhost:9001/actuator/beans 查看运行程序的Bean
                
                3. 使用Actuator关闭应该程序
                    curl -X POST http://localhost:9001/actuator/shutdown  (运行此命令必须设置:management.endpoint.shutdown.enabled = true)
                    

    Actuator 是Spring Boot 的一个非常重要的功能, Actuator 为开发人员提供了Spring Boot的运行状态信息,通过Actuator 可以查看程序的运行状态的信息
    

    Actuator详细介绍可以参考: https://blog.csdn.net/WYA1993/article/details/80540981

# 请求shutdown返回
{
    "message": "Shutting down, bye..."
}

http://localhost:9002/actuator/mappings
health
http://localhost:9002/actuator/health

{
    "status": "UP",
    "details": {
        "diskSpace": {
            "status": "UP",
            "details": {
                "total": 302643146752,
                "free": 118266159104,
                "threshold": 10485760
            }
        }
    }
}
beans

http://localhost:9002/actuator/beans

{
    "contexts": {
        "application": {
            "beans": {
                "endpointCachingOperationInvokerAdvisor": {
                    "aliases": [],
                    "scope": "singleton",
                    "type": "org.springframework.boot.actuate.endpoint.invoker.cache.CachingOperationInvokerAdvisor",
                    "resource": "class path resource [org/springframework/boot/actuate/autoconfigure/endpoint/EndpointAutoConfiguration.class]",
                    "dependencies": [
                        "environment"
                    ]
                },
  • scope
    • singleton
    • prototype
    • request
    • session

引入 remote-shell (已经引用)

  • 然而我测试的,不能用,哈哈哈,版本太高了。

boot整合jpa

引入依赖 web jpa mysql

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>

配置数据源

# 配置数据源
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/spring_cloud?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&serverTimezone=GMT%2B8
    username: root
    password: 123456

  jpa:
    hibernate:
      ddl-auto: create  # 第一次建表create  后面用update
    show-sql: true

创建实例类 dao service controller

entiry
@Entity
public class User {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;

	@Column(nullable = false,  unique = true)
	private String username;

	@Column
	private String password;
	}
service 和 dao
@Service
public class UserService {

    @Autowired
    private UserDao userRepository;

    public User findUserByName(String username){

        return userRepository.findByUsername(username);
    }

    public List<User> findAll(){
       return userRepository.findAll();
    }

    public User saveUser(User user){
      return  userRepository.save(user);
    }

    public Optional<User> findUserById(Long id){
        return userRepository.findById(id);
    }
    public User updateUser(User user){
       return userRepository.saveAndFlush(user);
    }
    public void deleteUser(Long id){
        userRepository.deleteById(id);
    }
}

public interface UserDao extends JpaRepository<User, Long> {

	User findByUsername(String username);
}

action
@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    UserService userService;

    @ApiOperation(value="用户列表", notes="用户列表")
    @RequestMapping(value={""}, method= RequestMethod.GET)
    public List<User> getUsers() {
        List<User> users = userService.findAll();
        return users;
    }

    @ApiOperation(value="创建用户", notes="创建用户")

    @RequestMapping(value="", method= RequestMethod.POST)
    public User postUser(@RequestBody User user) {
      return   userService.saveUser(user);

    }
//    @ApiOperation(value="获用户细信息", notes="根据url的id来获取详细信息")
//    @RequestMapping(value="/{id}", method= RequestMethod.GET)
//    public Optional<User> getUser(@PathVariable Long id) {
//        return userService.findUserById(id);
//    }

    //同时用两种接收 参数的方法
    @ApiOperation(value="更新信息", notes="根据url的id来指定更新用户信息")
    @RequestMapping(value="/{id}", method= RequestMethod.PUT)
    public User putUser(@PathVariable Long id, @RequestBody User user) {
        User user1 = new User();
        user1.setUsername(user.getUsername());
        user1.setPassword(user.getPassword());
        user1.setId(id);
       return userService.updateUser(user1);

    }
    @ApiOperation(value="删除用户", notes="根据url的id来指定删除用户")
    @RequestMapping(value="/{id}", method= RequestMethod.DELETE)
    public String deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
        return "success";
    }

    @ApiIgnore//使用该注解忽略这个API
    @RequestMapping(value = "/hi", method = RequestMethod.GET)
    public String  jsonTest() {
        return " hi you!";
    }



    @GetMapping("/username/{username}")
    public User getUser(@PathVariable("username")String username){
       return userService.findUserByName(username);

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值